diff --git a/.github/workflows/Lucene-Net-Tests-AllProjects.yml b/.github/workflows/Lucene-Net-Tests-AllProjects.yml
new file mode 100644
index 0000000000..7aedc0c06f
--- /dev/null
+++ b/.github/workflows/Lucene-Net-Tests-AllProjects.yml
@@ -0,0 +1,121 @@
+####################################################################################
+# DO NOT EDIT: This file was automatically generated by Generate-TestWorkflows.ps1
+####################################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+name: 'Lucene.Net.Tests.AllProjects'
+
+on:
+ workflow_dispatch:
+ pull_request:
+ paths:
+ - 'src/Lucene.Net.Tests.AllProjects/**/*'
+ - 'build/Dependencies.props'
+ - 'build/TestReferences.Common.*'
+ - 'TestTargetFrameworks.*'
+ - '*.sln'
+ - 'src/Lucene.Net.Tests.AllProjects/Directory.Build.*'
+ - 'src/Directory.Build.*'
+ - 'Directory.Build.*'
+
+ # Dependencies
+ - 'src/Lucene.Net/**/*'
+ - 'src/Lucene.Net.Analysis.Common/**/*'
+ - 'src/Lucene.Net.Memory/**/*'
+ - 'src/Lucene.Net.Queries/**/*'
+ - 'src/Lucene.Net.Highlighter/**/*'
+ - 'src/dotnet/Lucene.Net.ICU/**/*'
+ - 'src/Lucene.Net.Grouping/**/*'
+ - 'src/Lucene.Net.Join/**/*'
+ - 'src/Lucene.Net.Facet/**/*'
+ - 'src/Lucene.Net.Sandbox/**/*'
+ - 'src/Lucene.Net.QueryParser/**/*'
+ - 'src/Lucene.Net.Spatial/**/*'
+ - 'src/Lucene.Net.Benchmark/**/*'
+ - 'src/Lucene.Net.Classification/**/*'
+ - 'src/Lucene.Net.Codecs/**/*'
+ - 'src/Lucene.Net.Expressions/**/*'
+ - 'src/Lucene.Net.Misc/**/*'
+ - 'src/Lucene.Net.Replicator/**/*'
+ - 'src/Lucene.Net.Suggest/**/*'
+ - 'src/Lucene.Net.TestFramework/**/*'
+ - 'src/Lucene.Net.Analysis.OpenNLP/**/*'
+
+ - '!**/*.md'
+
+jobs:
+
+ Test:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [windows-latest, ubuntu-latest]
+ framework: [net5.0, netcoreapp2.1, net48]
+ platform: [x64]
+ configuration: [Release]
+ exclude:
+ - os: ubuntu-latest
+ framework: net48
+ - os: macos-latest
+ framework: net48
+ env:
+ project_path: './src/Lucene.Net.Tests.AllProjects/Lucene.Net.Tests.AllProjects.csproj'
+ trx_file_name: 'TestResults.trx'
+ md_file_name: 'TestResults.md' # Report file name for LiquidTestReports.Markdown
+
+ steps:
+ - uses: actions/checkout@v2
+
+ - name: Setup .NET 3.1 SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: '3.1.404'
+ if: ${{ startswith(matrix.framework, 'netcoreapp3.') }}
+
+ - name: Setup .NET 2.1 SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: '2.1.811'
+ if: ${{ startswith(matrix.framework, 'netcoreapp2.') }}
+
+ - name: Setup .NET 5 SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: '5.0.100'
+
+ - run: |
+ $project_name = [System.IO.Path]::GetFileNameWithoutExtension($env:project_path)
+ $test_results_artifact_name = "testresults_${{matrix.os}}_${{matrix.framework}}_${{matrix.platform}}_${{matrix.configuration}}"
+ Write-Host "Project Name: $project_name"
+ Write-Host "Results Artifact Name: $test_results_artifact_name"
+ echo "project_name=$project_name" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ echo "test_results_artifact_name=$test_results_artifact_name" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ # Title for LiquidTestReports.Markdown
+ echo "title=Test Run for $project_name - ${{matrix.framework}} - ${{matrix.platform}} - ${{matrix.os}}" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ shell: pwsh
+ - run: dotnet build ${{env.project_path}} --configuration ${{matrix.configuration}} --framework ${{matrix.framework}} /p:TestFrameworks=true
+ - run: dotnet test ${{env.project_path}} --configuration ${{matrix.configuration}} --framework ${{matrix.framework}} --no-build --no-restore --blame-hang --blame-hang-dump-type mini --blame-hang-timeout 20minutes --logger:"console;verbosity=normal" --logger:"trx;LogFileName=${{env.trx_file_name}}" --logger:"liquid.md;LogFileName=${{env.md_file_name}};Title=${{env.title}};" --results-directory:"${{github.workspace}}/${{env.test_results_artifact_name}}/${{env.project_name}}" -- RunConfiguration.TargetPlatform=${{matrix.platform}}
+ # upload reports as build artifacts
+ - name: Upload a Build Artifact
+ uses: actions/upload-artifact@v2
+ if: ${{always()}}
+ with:
+ name: '${{env.test_results_artifact_name}}'
+ path: '${{github.workspace}}/${{env.test_results_artifact_name}}'
+
diff --git a/Directory.Build.targets b/Directory.Build.targets
index c4be65f3b9..d7f22c70b4 100644
--- a/Directory.Build.targets
+++ b/Directory.Build.targets
@@ -106,6 +106,7 @@
$(DefineConstants);NETFRAMEWORK
$(DefineConstants);FEATURE_ARGITERATOR
$(DefineConstants);FEATURE_MEMORYMAPPEDFILESECURITY
+ $(DefineConstants);FEATURE_OPENNLP
$(DefineConstants);FEATURE_SERIALIZABLE_EXCEPTIONS
diff --git a/Lucene.Net.sln b/Lucene.Net.sln
index 55b54e8a96..cfa5b104c9 100644
--- a/Lucene.Net.sln
+++ b/Lucene.Net.sln
@@ -215,6 +215,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{4D0ED7D9
src\dotnet\Lucene.Net.CodeAnalysis\tools\uninstall.ps1 = src\dotnet\Lucene.Net.CodeAnalysis\tools\uninstall.ps1
EndProjectSection
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lucene.Net.Tests.AllProjects", "src\Lucene.Net.Tests.AllProjects\Lucene.Net.Tests.AllProjects.csproj", "{9880B87D-8D14-476B-B093-9C3AA0DA8B24}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -481,6 +483,10 @@ Global
{5CD4D4E8-6132-4384-98FC-6AB1C97E0B80}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5CD4D4E8-6132-4384-98FC-6AB1C97E0B80}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5CD4D4E8-6132-4384-98FC-6AB1C97E0B80}.Release|Any CPU.Build.0 = Release|Any CPU
+ {9880B87D-8D14-476B-B093-9C3AA0DA8B24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {9880B87D-8D14-476B-B093-9C3AA0DA8B24}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {9880B87D-8D14-476B-B093-9C3AA0DA8B24}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {9880B87D-8D14-476B-B093-9C3AA0DA8B24}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/build/Dependencies.props b/build/Dependencies.props
index bba7346471..bfd0031020 100644
--- a/build/Dependencies.props
+++ b/build/Dependencies.props
@@ -38,7 +38,7 @@
$(ICU4NPackageVersion)
$(ICU4NPackageVersion)
$(ICU4NPackageVersion)
- 2.0.0-beta-0013
+ 2.0.0-beta-0015
1.0.9
2.0.0
2.0.0
diff --git a/build/azure-templates/publish-test-results-for-test-projects.yml b/build/azure-templates/publish-test-results-for-test-projects.yml
index 40cf1c02c2..4d6751c8bf 100644
--- a/build/azure-templates/publish-test-results-for-test-projects.yml
+++ b/build/azure-templates/publish-test-results-for-test-projects.yml
@@ -1,4 +1,4 @@
-# Licensed to the Apache Software Foundation (ASF) under one
+# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
@@ -164,6 +164,16 @@ steps:
testResultsArtifactName: '${{ parameters.testResultsArtifactName }}'
testResultsFileName: '${{ parameters.testResultsFileName }}'
+- template: publish-test-results.yml
+ parameters:
+ testProjectName: 'Lucene.Net.Tests.AllProjects'
+ osName: '${{ parameters.osName }}'
+ framework: '${{ parameters.framework }}'
+ vsTestPlatform: '${{ parameters.vsTestPlatform }}'
+ testResultsFormat: '${{ parameters.testResultsFormat }}'
+ testResultsArtifactName: '${{ parameters.testResultsArtifactName }}'
+ testResultsFileName: '${{ parameters.testResultsFileName }}'
+
- template: publish-test-results.yml
parameters:
testProjectName: 'Lucene.Net.Tests.Analysis.Common'
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Ar/ArabicAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Ar/ArabicAnalyzer.cs
index 29dba1091f..7e7b1ff141 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Ar/ArabicAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Ar/ArabicAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Standard;
@@ -72,11 +72,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(ArabicAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Bg/BulgarianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Bg/BulgarianAnalyzer.cs
index 58541c9281..49202b66c9 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Bg/BulgarianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Bg/BulgarianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Standard;
@@ -65,11 +65,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(BulgarianAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Br/BrazilianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Br/BrazilianAnalyzer.cs
index b6048b88f5..94dd517b4a 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Br/BrazilianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Br/BrazilianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Standard;
@@ -64,11 +64,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Ca/CatalanAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Ca/CatalanAnalyzer.cs
index 92457bfe86..f681d43c52 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Ca/CatalanAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Ca/CatalanAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -70,11 +70,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(CatalanAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/CharFilter/HTMLStripCharFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/CharFilter/HTMLStripCharFilter.cs
index e2c3778c06..e70a392381 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/CharFilter/HTMLStripCharFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/CharFilter/HTMLStripCharFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Diagnostics;
@@ -31136,16 +31136,17 @@ private char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
///
@@ -31370,12 +31371,7 @@ private int NextChar()
if (matchLength <= 7)
{ // 0x10FFFF = 1114111: max 7 decimal chars
string decimalCharRef = YyText();
- int codePoint = 0;
- try
- {
- codePoint = int.Parse(decimalCharRef, CultureInfo.InvariantCulture);
- }
- catch (Exception /*e*/)
+ if (!int.TryParse(decimalCharRef, NumberStyles.Integer, CultureInfo.InvariantCulture, out int codePoint))
{
if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing code point '{0}'", decimalCharRef);
}
@@ -31630,14 +31626,9 @@ private int NextChar()
{ // 10FFFF: max 6 hex chars
string hexCharRef
= new string(zzBuffer, zzStartRead + 1, matchLength - 1);
- int codePoint = 0;
- try
+ if (!int.TryParse(hexCharRef, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int codePoint))
{
- codePoint = int.Parse(hexCharRef, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
- }
- catch (Exception e)
- {
- if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing hex code point '{0}'", e);
+ if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing hex code point '{0}'", hexCharRef);
}
if (codePoint <= 0x10FFFF)
{
@@ -31898,7 +31889,7 @@ string hexCharRef
{
highSurrogate = (char)int.Parse(surrogatePair.Substring(2, 6 - 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{ // should never happen
if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing high surrogate '{0}'", surrogatePair.Substring(2, 6 - 2));
}
@@ -31906,10 +31897,11 @@ string hexCharRef
{
outputSegment.UnsafeWrite((char)int.Parse(surrogatePair.Substring(10, 14 - 10), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{ // should never happen
if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing low surrogate '{0}'", surrogatePair.Substring(10, 14 - 10));
}
+
// add (previously matched input length) + (this match length) - (substitution length)
cumulativeDiff += inputSegment.Length + YyLength - 2;
// position the correction at (already output length) + (substitution length)
@@ -31928,7 +31920,7 @@ string hexCharRef
{
highSurrogate = (char)int.Parse(surrogatePair.Substring(2, 6 - 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{ // should never happen
if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing high surrogate '{0}'", surrogatePair.Substring(2, 6 - 2));
}
@@ -31936,7 +31928,7 @@ string hexCharRef
{ // Low surrogates are in decimal range [56320, 57343]
lowSurrogate = (char)int.Parse(surrogatePair.Substring(9, 14 - 9), CultureInfo.InvariantCulture);
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{ // should never happen
if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing low surrogate '{0}'", surrogatePair.Substring(9, 14 - 9));
}
@@ -31967,7 +31959,7 @@ string hexCharRef
{ // High surrogates are in decimal range [55296, 56319]
highSurrogate = (char)int.Parse(surrogatePair.Substring(1, 6 - 1), CultureInfo.InvariantCulture);
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{ // should never happen
if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing high surrogate '{0}'", surrogatePair.Substring(1, 6 - 1));
}
@@ -31979,7 +31971,7 @@ string hexCharRef
{
outputSegment.UnsafeWrite((char)int.Parse(surrogatePair.Substring(10, 14 - 10), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{ // should never happen
if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing low surrogate '{0}'", surrogatePair.Substring(10, 14 - 10));
}
@@ -32005,7 +31997,7 @@ string hexCharRef
{ // High surrogates are in decimal range [55296, 56319]
highSurrogate = (char)int.Parse(surrogatePair.Substring(1, 6 - 1), CultureInfo.InvariantCulture);
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{ // should never happen
if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing high surrogate '{0}'", surrogatePair.Substring(1, 6 - 1));
}
@@ -32016,7 +32008,7 @@ string hexCharRef
{ // Low surrogates are in decimal range [56320, 57343]
lowSurrogate = (char)int.Parse(surrogatePair.Substring(9, 14 - 9), CultureInfo.InvariantCulture);
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{ // should never happen
if (Debugging.AssertsEnabled) Debugging.Assert(false, "Exception parsing low surrogate '{0}'", surrogatePair.Substring(9, 14 - 9));
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/CharFilter/NormalizeCharMap.cs b/src/Lucene.Net.Analysis.Common/Analysis/CharFilter/NormalizeCharMap.cs
index 7620252446..e0eff53fae 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/CharFilter/NormalizeCharMap.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/CharFilter/NormalizeCharMap.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
using Lucene.Net.Util.Fst;
@@ -66,10 +66,10 @@ private NormalizeCharMap(FST map)
}
//System.out.println("cached " + cachedRootArcs.size() + " root arcs");
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
// Bogus FST IOExceptions!! (will never happen)
- throw new Exception("Should never happen", ioe);
+ throw RuntimeException.Create("Should never happen", ioe);
}
}
}
@@ -130,10 +130,10 @@ public virtual NormalizeCharMap Build()
map = builder.Finish();
pendingPairs.Clear();
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
// Bogus FST IOExceptions!! (will never happen)
- throw new Exception("Should never happen", ioe);
+ throw RuntimeException.Create("Should never happen", ioe);
}
return new NormalizeCharMap(map);
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Cjk/CJKAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Cjk/CJKAnalyzer.cs
index 6af3a548e4..3e7b312632 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Cjk/CJKAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Cjk/CJKAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Analysis.Util;
@@ -56,11 +56,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(CJKAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Ckb/SoraniAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Ckb/SoraniAnalyzer.cs
index 98230806a3..9bd157bc42 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Ckb/SoraniAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Ckb/SoraniAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Standard;
@@ -61,11 +61,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Compound/CompoundWordTokenFilterBase.cs b/src/Lucene.Net.Analysis.Common/Analysis/Compound/CompoundWordTokenFilterBase.cs
index 50819c4e88..f17e2e0df2 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Compound/CompoundWordTokenFilterBase.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Compound/CompoundWordTokenFilterBase.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N.Text;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
@@ -90,17 +90,17 @@ protected CompoundWordTokenFilterBase(LuceneVersion matchVersion, TokenStream in
this.m_tokens = new Queue();
if (minWordSize < 0)
{
- throw new ArgumentException("minWordSize cannot be negative");
+ throw new ArgumentOutOfRangeException(nameof(minWordSize), "minWordSize cannot be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.m_minWordSize = minWordSize;
if (minSubwordSize < 0)
{
- throw new ArgumentException("minSubwordSize cannot be negative");
+ throw new ArgumentOutOfRangeException(nameof(minSubwordSize), "minSubwordSize cannot be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.m_minSubwordSize = minSubwordSize;
if (maxSubwordSize < 0)
{
- throw new ArgumentException("maxSubwordSize cannot be negative");
+ throw new ArgumentOutOfRangeException(nameof(maxSubwordSize), "maxSubwordSize cannot be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.m_maxSubwordSize = maxSubwordSize;
this.m_onlyLongestMatch = onlyLongestMatch;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Compound/DictionaryCompoundWordTokenFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Compound/DictionaryCompoundWordTokenFilter.cs
index 37d8f82875..8781a592c1 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Compound/DictionaryCompoundWordTokenFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Compound/DictionaryCompoundWordTokenFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
using System;
@@ -56,9 +56,9 @@ public class DictionaryCompoundWordTokenFilter : CompoundWordTokenFilterBase
public DictionaryCompoundWordTokenFilter(LuceneVersion matchVersion, TokenStream input, CharArraySet dictionary)
: base(matchVersion, input, dictionary)
{
- if (dictionary == null)
+ if (dictionary is null)
{
- throw new ArgumentException("dictionary cannot be null");
+ throw new ArgumentNullException(nameof(dictionary), "dictionary cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
}
@@ -85,9 +85,9 @@ public DictionaryCompoundWordTokenFilter(LuceneVersion matchVersion, TokenStream
public DictionaryCompoundWordTokenFilter(LuceneVersion matchVersion, TokenStream input, CharArraySet dictionary, int minWordSize, int minSubwordSize, int maxSubwordSize, bool onlyLongestMatch)
: base(matchVersion, input, dictionary, minWordSize, minSubwordSize, maxSubwordSize, onlyLongestMatch)
{
- if (dictionary == null)
+ if (dictionary is null)
{
- throw new ArgumentException("dictionary cannot be null");
+ throw new ArgumentNullException(nameof(dictionary), "dictionary cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Compound/Hyphenation/TernaryTree.cs b/src/Lucene.Net.Analysis.Common/Analysis/Compound/Hyphenation/TernaryTree.cs
index 7dd428ac5f..d16d1e9f6d 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Compound/Hyphenation/TernaryTree.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Compound/Hyphenation/TernaryTree.cs
@@ -775,7 +775,7 @@ public bool MoveNext()
public void Reset()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
#endregion
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Core/KeywordTokenizer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Core/KeywordTokenizer.cs
index 896c25c0e9..4f48fb14ac 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Core/KeywordTokenizer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Core/KeywordTokenizer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;
using System;
@@ -50,7 +50,7 @@ public KeywordTokenizer(TextReader input, int bufferSize)
if (bufferSize <= 0)
{
- throw new ArgumentException("bufferSize must be > 0");
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), "bufferSize must be > 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
termAtt.ResizeBuffer(bufferSize);
}
@@ -63,7 +63,7 @@ public KeywordTokenizer(AttributeSource.AttributeFactory factory, TextReader inp
if (bufferSize <= 0)
{
- throw new ArgumentException("bufferSize must be > 0");
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), "bufferSize must be > 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
termAtt.ResizeBuffer(bufferSize);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Cz/CzechAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Cz/CzechAnalyzer.cs
index 29307f9817..dd988ed339 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Cz/CzechAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Cz/CzechAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Standard;
@@ -72,11 +72,11 @@ private static CharArraySet LoadDefaultSet() // LUCENENET: Avoid static construc
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Da/DanishAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Da/DanishAnalyzer.cs
index 4a2f2171b1..52ad8c9679 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Da/DanishAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Da/DanishAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -63,11 +63,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/De/GermanAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/De/GermanAnalyzer.cs
index 86a8fa3fb2..6d76dcb6ba 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/De/GermanAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/De/GermanAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -99,11 +99,11 @@ private static CharArraySet LoadDefaultSet() // LUCENENET: Avoid static construc
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/El/GreekAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/El/GreekAnalyzer.cs
index 2ceab4ef17..d0b9ae0fae 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/El/GreekAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/El/GreekAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Analysis.Util;
@@ -64,11 +64,11 @@ private static CharArraySet LoadDefaultSet() // LUCENENET: Avoid static construc
{
return LoadStopwordSet(false, typeof(GreekAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/En/KStemmer.cs b/src/Lucene.Net.Analysis.Common/Analysis/En/KStemmer.cs
index 96d92b4030..940c7a52e5 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/En/KStemmer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/En/KStemmer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N.Text;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
@@ -405,7 +405,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + exceptionWords[i] + "] already in dictionary 1");
+ throw RuntimeException.Create("Warning: Entry [" + exceptionWords[i] + "] already in dictionary 1");
}
}
@@ -418,7 +418,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + directConflations[i][0] + "] already in dictionary 2");
+ throw RuntimeException.Create("Warning: Entry [" + directConflations[i][0] + "] already in dictionary 2");
}
}
@@ -431,7 +431,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + countryNationality[i][0] + "] already in dictionary 3");
+ throw RuntimeException.Create("Warning: Entry [" + countryNationality[i][0] + "] already in dictionary 3");
}
}
@@ -448,7 +448,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + array[i] + "] already in dictionary 4");
+ throw RuntimeException.Create("Warning: Entry [" + array[i] + "] already in dictionary 4");
}
}
@@ -461,7 +461,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + array[i] + "] already in dictionary 4");
+ throw RuntimeException.Create("Warning: Entry [" + array[i] + "] already in dictionary 4");
}
}
@@ -474,7 +474,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + array[i] + "] already in dictionary 4");
+ throw RuntimeException.Create("Warning: Entry [" + array[i] + "] already in dictionary 4");
}
}
@@ -487,7 +487,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + array[i] + "] already in dictionary 4");
+ throw RuntimeException.Create("Warning: Entry [" + array[i] + "] already in dictionary 4");
}
}
@@ -500,7 +500,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + array[i] + "] already in dictionary 4");
+ throw RuntimeException.Create("Warning: Entry [" + array[i] + "] already in dictionary 4");
}
}
@@ -513,7 +513,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + array[i] + "] already in dictionary 4");
+ throw RuntimeException.Create("Warning: Entry [" + array[i] + "] already in dictionary 4");
}
}
@@ -526,7 +526,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + array[i] + "] already in dictionary 4");
+ throw RuntimeException.Create("Warning: Entry [" + array[i] + "] already in dictionary 4");
}
}
@@ -538,7 +538,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + KStemData8.data[i] + "] already in dictionary 4");
+ throw RuntimeException.Create("Warning: Entry [" + KStemData8.data[i] + "] already in dictionary 4");
}
}
@@ -550,7 +550,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + supplementDict[i] + "] already in dictionary 5");
+ throw RuntimeException.Create("Warning: Entry [" + supplementDict[i] + "] already in dictionary 5");
}
}
@@ -562,7 +562,7 @@ private static CharArrayMap InitializeDictHash()
}
else
{
- throw new Exception("Warning: Entry [" + properNouns[i] + "] already in dictionary 6");
+ throw RuntimeException.Create("Warning: Entry [" + properNouns[i] + "] already in dictionary 6");
}
}
@@ -766,7 +766,7 @@ private bool Lookup()
// lookups.add(thisLookup); if (!added) {
// System.out.println("######extra lookup:" + thisLookup); // occaasional
// extra lookups aren't necessarily errors... could happen by diff
- // manipulations // throw new RuntimeException("######extra lookup:" +
+ // manipulations // throw RuntimeException.Create("######extra lookup:" +
// thisLookup); } else { // System.out.println("new lookup:" + thisLookup);
// }
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/En/PorterStemmer.cs b/src/Lucene.Net.Analysis.Common/Analysis/En/PorterStemmer.cs
index 2d1b511cd1..72dab04135 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/En/PorterStemmer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/En/PorterStemmer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Support;
using Lucene.Net.Util;
using System;
@@ -861,7 +861,7 @@ public virtual bool Stem(int i0)
// }
// }
// }
- // catch (IOException e)
+ // catch (Exception e) when (ex.IsIOException())
// {
// Console.WriteLine("error reading " + args[i]);
// Console.WriteLine(e.ToString());
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Es/SpanishAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Es/SpanishAnalyzer.cs
index b7b51d394f..e1fb57665a 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Es/SpanishAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Es/SpanishAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -71,11 +71,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Eu/BasqueAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Eu/BasqueAnalyzer.cs
index 88fcc3e3e8..1976be7229 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Eu/BasqueAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Eu/BasqueAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -58,11 +58,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(BasqueAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Fa/PersianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Fa/PersianAnalyzer.cs
index c225756d63..4426a06d12 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Fa/PersianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Fa/PersianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Ar;
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Standard;
@@ -71,11 +71,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(PersianAnalyzer), DEFAULT_STOPWORD_FILE, STOPWORDS_COMMENT);
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Fi/FinnishAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Fi/FinnishAnalyzer.cs
index 2026df2acd..ffcef86a5a 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Fi/FinnishAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Fi/FinnishAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -63,11 +63,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Fr/FrenchAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Fr/FrenchAnalyzer.cs
index b17e898868..97ae77111e 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Fr/FrenchAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Fr/FrenchAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -121,11 +121,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Ga/IrishAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Ga/IrishAnalyzer.cs
index 5b0c6178f2..04ccbc4296 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Ga/IrishAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Ga/IrishAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -75,11 +75,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(IrishAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Gl/GalicianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Gl/GalicianAnalyzer.cs
index eff44039f8..e7c690edd5 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Gl/GalicianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Gl/GalicianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Standard;
@@ -61,11 +61,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Hi/HindiAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Hi/HindiAnalyzer.cs
index 62bc54ecdf..769517d4df 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Hi/HindiAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Hi/HindiAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.In;
using Lucene.Net.Analysis.Miscellaneous;
@@ -68,11 +68,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(HindiAnalyzer), DEFAULT_STOPWORD_FILE, STOPWORDS_COMMENT);
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Hu/HungarianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Hu/HungarianAnalyzer.cs
index b7f69a9450..9da93f3248 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Hu/HungarianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Hu/HungarianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -63,11 +63,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Dictionary.cs b/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Dictionary.cs
index b175b58867..bb13c63979 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Dictionary.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Dictionary.cs
@@ -281,9 +281,9 @@ internal virtual Int32sRef Lookup(FST fst, char[] word, int offset, i
return output;
}
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.Message, bogus);
+ throw RuntimeException.Create(bogus);
}
}
@@ -352,7 +352,7 @@ private void ReadAffixFile(Stream affixStream, Encoding decoder)
string[] parts = whitespacePattern.Split(line).TrimEnd();
if (parts.Length != 2)
{
- throw new FormatException(string.Format("Illegal CIRCUMFIX declaration, line {0}", lineNumber));
+ throw new ParseException("Illegal CIRCUMFIX declaration", lineNumber);
}
circumfix = flagParsingStrategy.ParseFlag(parts[1]);
}
@@ -361,7 +361,7 @@ private void ReadAffixFile(Stream affixStream, Encoding decoder)
string[] parts = whitespacePattern.Split(line).TrimEnd();
if (parts.Length != 2)
{
- throw new FormatException(string.Format("Illegal KEEPCASE declaration, line {0}", lineNumber));
+ throw new ParseException("Illegal KEEPCASE declaration", lineNumber);
}
keepcase = flagParsingStrategy.ParseFlag(parts[1]);
}
@@ -370,7 +370,7 @@ private void ReadAffixFile(Stream affixStream, Encoding decoder)
string[] parts = whitespacePattern.Split(line).TrimEnd();
if (parts.Length != 2)
{
- throw new FormatException(string.Format("Illegal NEEDAFFIX declaration, line {0}", lineNumber));
+ throw new ParseException("Illegal NEEDAFFIX declaration", lineNumber);
}
needaffix = flagParsingStrategy.ParseFlag(parts[1]);
}
@@ -379,7 +379,7 @@ private void ReadAffixFile(Stream affixStream, Encoding decoder)
string[] parts = whitespacePattern.Split(line).TrimEnd();
if (parts.Length != 2)
{
- throw new FormatException(string.Format("Illegal ONLYINCOMPOUND declaration, line {0}", lineNumber));
+ throw new ParseException("Illegal ONLYINCOMPOUND declaration", lineNumber);
}
onlyincompound = flagParsingStrategy.ParseFlag(parts[1]);
}
@@ -388,7 +388,7 @@ private void ReadAffixFile(Stream affixStream, Encoding decoder)
string[] parts = whitespacePattern.Split(line).TrimEnd();
if (parts.Length != 2)
{
- throw new FormatException(string.Format("Illegal IGNORE declaration, line {0}", lineNumber));
+ throw new ParseException("Illegal IGNORE declaration", lineNumber);
}
ignore = parts[1].ToCharArray();
Array.Sort(ignore);
@@ -400,10 +400,10 @@ private void ReadAffixFile(Stream affixStream, Encoding decoder)
string type = parts[0];
if (parts.Length != 2)
{
- throw new FormatException(string.Format("Illegal {0} declaration, line {1}", type, lineNumber));
+ throw new ParseException(string.Format("Illegal {0} declaration", type), lineNumber);
}
int num = int.Parse(parts[1], CultureInfo.InvariantCulture);
- FST res = ParseConversions(reader, num);
+ FST res = ParseConversions(reader, num, lineNumber); // LUCENENET: Pass linenumber so we can throw it
if (type.Equals("ICONV", StringComparison.Ordinal))
{
iconv = res;
@@ -532,7 +532,7 @@ private void ParseAffix(JCG.SortedDictionary> affixes,
// condition is optional
if (ruleArgs.Length < 4)
{
- throw new FormatException("The affix file contains a rule with less than four elements: " + line /*, reader.LineNumber */);// LUCENENET TODO: LineNumberReader
+ throw new ParseException("The affix file contains a rule with less than four elements: " + line, 0 /*, reader.LineNumber */);// LUCENENET TODO: LineNumberReader
}
char flag = flagParsingStrategy.ParseFlag(ruleArgs[1]);
@@ -596,7 +596,7 @@ private void ParseAffix(JCG.SortedDictionary> affixes,
patternIndex = patterns.Count;
if (patternIndex > short.MaxValue)
{
- throw new NotSupportedException("Too many patterns, please report this to dev@lucene.apache.org");
+ throw UnsupportedOperationException.Create("Too many patterns, please report this to dev@lucene.apache.org");
}
seenPatterns[regex] = patternIndex;
CharacterRunAutomaton pattern = new CharacterRunAutomaton((new RegExp(regex, RegExpSyntax.NONE)).ToAutomaton());
@@ -609,7 +609,7 @@ private void ParseAffix(JCG.SortedDictionary> affixes,
seenStrips[strip] = stripOrd;
if (stripOrd > char.MaxValue)
{
- throw new NotSupportedException("Too many unique strips, please report this to dev@lucene.apache.org");
+ throw UnsupportedOperationException.Create("Too many unique strips, please report this to dev@lucene.apache.org");
}
}
@@ -628,7 +628,7 @@ private void ParseAffix(JCG.SortedDictionary> affixes,
else if (appendFlagsOrd > short.MaxValue)
{
// this limit is probably flexible, but its a good sanity check too
- throw new NotSupportedException("Too many unique append flags, please report this to dev@lucene.apache.org");
+ throw UnsupportedOperationException.Create("Too many unique append flags, please report this to dev@lucene.apache.org");
}
affixWriter.WriteInt16((short)flag);
@@ -659,7 +659,7 @@ private void ParseAffix(JCG.SortedDictionary> affixes,
}
}
- private FST ParseConversions(TextReader reader, int num)
+ private FST ParseConversions(TextReader reader, int num, int lineNumber)
{
IDictionary mappings = new JCG.SortedDictionary(StringComparer.Ordinal);
@@ -669,11 +669,11 @@ private FST ParseConversions(TextReader reader, int num)
string[] parts = whitespacePattern.Split(line).TrimEnd();
if (parts.Length != 3)
{
- throw new FormatException("invalid syntax: " + line /*, reader.LineNumber */); // LUCENENET TODO: LineNumberReader
+ throw new ParseException("invalid syntax: " + line, lineNumber /*, reader.LineNumber */); // LUCENENET TODO: LineNumberReader
}
if (mappings.Put(parts[1], parts[2]) != null)
{
- throw new InvalidOperationException("duplicate mapping specified for: " + parts[1]);
+ throw IllegalStateException.Create("duplicate mapping specified for: " + parts[1]);
}
}
@@ -723,7 +723,7 @@ internal static string GetDictionaryEncoding(Stream affix)
// this test only at the end as ineffective but would allow lines only containing spaces:
if (ch < 0)
{
- throw new FormatException("Unexpected end of affix file." /*, 0*/);
+ throw new ParseException("Unexpected end of affix file.", 0);
}
continue;
}
@@ -1197,7 +1197,7 @@ private string GetAliasValue(int id)
{
return aliases[id - 1];
}
- catch (IndexOutOfRangeException ex)
+ catch (Exception ex) when (ex.IsIndexOutOfBoundsException())
{
throw new ArgumentException("Bad flag alias number:" + id, ex);
}
@@ -1392,9 +1392,9 @@ internal virtual string CleanInput(string input, StringBuilder reuse)
{
ApplyMappings(iconv, reuse);
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.Message, bogus);
+ throw RuntimeException.Create(bogus);
}
if (ignoreCase)
{
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/HunspellStemFilterFactory.cs b/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/HunspellStemFilterFactory.cs
index 1752eab242..c2d6493a16 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/HunspellStemFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/HunspellStemFilterFactory.cs
@@ -94,7 +94,7 @@ public virtual void Inform(IResourceLoader loader)
this.dictionary = new Dictionary(affix, dictionaries, ignoreCase);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsParseException())
{
throw new IOException("Unable to load hunspell data! [dictionary=" + dictionaries + ",affix=" + affixFile + "]", e);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Stemmer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Stemmer.cs
index 41d31fc438..ecf3857804 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Stemmer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Stemmer.cs
@@ -226,9 +226,9 @@ private IList DoStem(char[] word, int length, bool caseVariant)
{
stems.AddRange(Stem(word, length, -1, -1, -1, 0, true, true, false, false, caseVariant));
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.ToString(), bogus);
+ throw RuntimeException.Create(bogus);
}
return stems;
}
@@ -297,9 +297,9 @@ private CharsRef NewStem(char[] buffer, int length, Int32sRef forms, int formID)
{
Dictionary.ApplyMappings(dictionary.oconv, scratchSegment);
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.Message, bogus);
+ throw RuntimeException.Create(bogus);
}
char[] cleaned = new char[scratchSegment.Length];
scratchSegment.CopyTo(0, cleaned, 0, cleaned.Length);
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Hy/ArmenianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Hy/ArmenianAnalyzer.cs
index f37d6f33f1..ecc7b6f7aa 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Hy/ArmenianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Hy/ArmenianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -58,11 +58,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(ArmenianAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Id/IndonesianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Id/IndonesianAnalyzer.cs
index e6c8e2c21b..3c82ece464 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Id/IndonesianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Id/IndonesianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Standard;
@@ -54,11 +54,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(IndonesianAnalyzer), DEFAULT_STOPWORD_FILE, "#");
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/It/ItalianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/It/ItalianAnalyzer.cs
index 8a0576996c..0832d1c0b8 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/It/ItalianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/It/ItalianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -78,11 +78,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Lv/LatvianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Lv/LatvianAnalyzer.cs
index 23827a4825..4dcf8c0a70 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Lv/LatvianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Lv/LatvianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Standard;
@@ -61,11 +61,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/CapitalizationFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/CapitalizationFilter.cs
index 8cf86d84fa..4677dbb485 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/CapitalizationFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/CapitalizationFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -127,15 +127,15 @@ public CapitalizationFilter(TokenStream @in, bool onlyFirstWord, CharArraySet ke
// original tests did not. Adding them anyway because there is no downside to this.
if (minWordLength < 0)
{
- throw new ArgumentOutOfRangeException("minWordLength must be greater than or equal to zero");
+ throw new ArgumentOutOfRangeException(nameof(minWordLength), "minWordLength must be greater than or equal to zero");
}
if (maxWordCount < 1)
{
- throw new ArgumentOutOfRangeException("maxWordCount must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(maxWordCount), "maxWordCount must be greater than zero");
}
if (maxTokenLength < 1)
{
- throw new ArgumentOutOfRangeException("maxTokenLength must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(maxTokenLength), "maxTokenLength must be greater than zero");
}
this.onlyFirstWord = onlyFirstWord;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/CodepointCountFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/CodepointCountFilter.cs
index 3de10953d9..3ebeb76bf7 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/CodepointCountFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/CodepointCountFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
@@ -48,16 +48,13 @@ public sealed class CodepointCountFilter : FilteringTokenFilter
public CodepointCountFilter(LuceneVersion version, TokenStream @in, int min, int max)
: base(version, @in)
{
- // LUCENENET: The guard clauses were copied here from a later version of Lucene.
- // Apparently, the tests were not ported from 4.8.0 because they expected this and the
- // original tests did not. Adding them anyway because there is no downside to this.
if (min < 0)
{
- throw new ArgumentOutOfRangeException("minimum length must be greater than or equal to zero");
+ throw new ArgumentOutOfRangeException(nameof(min), "minimum length must be greater than or equal to zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (min > max)
{
- throw new ArgumentOutOfRangeException("maximum length must not be greater than minimum length");
+ throw new ArgumentOutOfRangeException(nameof(min), "maximum length must not be greater than minimum length"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.min = min;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LengthFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LengthFilter.cs
index dacc5ea051..490c8a4b69 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LengthFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LengthFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
@@ -42,11 +42,11 @@ public LengthFilter(LuceneVersion version, bool enablePositionIncrements, TokenS
{
if (min < 0)
{
- throw new ArgumentOutOfRangeException("minimum length must be greater than or equal to zero");
+ throw new ArgumentOutOfRangeException(nameof(min), "minimum length must be greater than or equal to zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (min > max)
{
- throw new ArgumentOutOfRangeException("maximum length must not be greater than minimum length");
+ throw new ArgumentOutOfRangeException(nameof(max), "maximum length must not be greater than minimum length"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.min = min;
this.max = max;
@@ -66,11 +66,11 @@ public LengthFilter(LuceneVersion version, TokenStream @in, int min, int max)
{
if (min < 0)
{
- throw new ArgumentOutOfRangeException("minimum length must be greater than or equal to zero");
+ throw new ArgumentOutOfRangeException(nameof(min), "minimum length must be greater than or equal to zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (min > max)
{
- throw new ArgumentOutOfRangeException("maximum length must not be greater than minimum length");
+ throw new ArgumentOutOfRangeException(nameof(max), "maximum length must not be greater than minimum length"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.min = min;
this.max = max;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LimitTokenCountFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LimitTokenCountFilter.cs
index 573e730d8d..6b6792096e 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LimitTokenCountFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LimitTokenCountFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using System;
namespace Lucene.Net.Analysis.Miscellaneous
@@ -64,7 +64,7 @@ public LimitTokenCountFilter(TokenStream @in, int maxTokenCount, bool consumeAll
{
if (maxTokenCount < 1)
{
- throw new ArgumentOutOfRangeException("maxTokenCount must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(maxTokenCount), "maxTokenCount must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.maxTokenCount = maxTokenCount;
this.consumeAllTokens = consumeAllTokens;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LimitTokenPositionFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LimitTokenPositionFilter.cs
index 0f6ade1c42..6b680643a7 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LimitTokenPositionFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LimitTokenPositionFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
@@ -69,7 +69,7 @@ public LimitTokenPositionFilter(TokenStream @in, int maxTokenPosition, bool cons
{
if (maxTokenPosition < 1)
{
- throw new ArgumentException("maxTokenPosition must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(maxTokenPosition), "maxTokenPosition must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.maxTokenPosition = maxTokenPosition;
this.consumeAllTokens = consumeAllTokens;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/PatternAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/PatternAnalyzer.cs
index 471e5464e9..d76ee694d3 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/PatternAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/PatternAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
@@ -157,9 +157,9 @@ public sealed class PatternAnalyzer : Analyzer
/// lists .
public PatternAnalyzer(LuceneVersion matchVersion, Regex pattern, bool toLowerCase, CharArraySet stopWords)
{
- if (pattern == null)
+ if (pattern is null)
{
- throw new ArgumentException("pattern must not be null");
+ throw new ArgumentNullException(nameof(pattern), "pattern must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (EqPattern(NON_WORD_PATTERN, pattern))
@@ -377,7 +377,7 @@ public override bool IncrementToken()
{
if (!initialized)
{
- throw new InvalidOperationException("Consumer did not call reset().");
+ throw IllegalStateException.Create("Consumer did not call Reset().");
}
if (matcher == null)
{
@@ -494,7 +494,7 @@ public override bool IncrementToken()
{
if (str == null)
{
- throw new InvalidOperationException("Consumer did not call reset().");
+ throw IllegalStateException.Create("Consumer did not call Reset().");
}
ClearAttributes();
// cache loop instance vars (performance)
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/TruncateTokenFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/TruncateTokenFilter.cs
index dde5a53555..8139af828b 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/TruncateTokenFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/TruncateTokenFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
@@ -40,7 +40,7 @@ public TruncateTokenFilter(TokenStream input, int length)
{
if (length < 1)
{
- throw new ArgumentOutOfRangeException("length parameter must be a positive number: " + length);
+ throw new ArgumentOutOfRangeException(nameof(length),"length parameter must be a positive number: " + length); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.length = length;
this.termAttribute = AddAttribute();
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/NGram/EdgeNGramTokenFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/NGram/EdgeNGramTokenFilter.cs
index 7ccff4153f..fd8def13c7 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/NGram/EdgeNGramTokenFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/NGram/EdgeNGramTokenFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
@@ -99,25 +99,21 @@ public static Side GetSide(string sideName)
public EdgeNGramTokenFilter(LuceneVersion version, TokenStream input, Side side, int minGram, int maxGram)
: base(input)
{
-
- //if (version == null)
- //{
- // throw new ArgumentException("version must not be null");
- //}
+ // LUCENENET specific - version cannot be null because it is a value type.
if (version.OnOrAfter(LuceneVersion.LUCENE_44) && side == Side.BACK)
{
throw new ArgumentException("Side.BACK is not supported anymore as of Lucene 4.4, use ReverseStringFilter up-front and afterward");
}
- if (!Enum.IsDefined(typeof(Side), side))
+ if (!side.IsDefined())
{
- throw new ArgumentException("sideLabel must be either front or back");
+ throw new ArgumentOutOfRangeException(nameof(side), "sideLabel must be either front or back"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minGram < 1)
{
- throw new ArgumentException("minGram must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(minGram), "minGram must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minGram > maxGram)
@@ -243,4 +239,16 @@ public override void Reset()
savePosIncr = 0;
}
}
+
+ // LUCENENET: added this to avoid the Enum.IsDefined() method, which requires boxing
+ internal static partial class SideExtensions
+ {
+ internal static bool IsDefined(this EdgeNGramTokenFilter.Side side)
+ {
+ return side >= EdgeNGramTokenFilter.Side.FRONT &&
+#pragma warning disable CS0612 // Type or member is obsolete
+ side <= EdgeNGramTokenFilter.Side.BACK;
+#pragma warning restore CS0612 // Type or member is obsolete
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/NGram/Lucene43EdgeNGramTokenizer.cs b/src/Lucene.Net.Analysis.Common/Analysis/NGram/Lucene43EdgeNGramTokenizer.cs
index b1bdacd6da..11f4a5c936 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/NGram/Lucene43EdgeNGramTokenizer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/NGram/Lucene43EdgeNGramTokenizer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;
using System;
@@ -159,19 +159,16 @@ public Lucene43EdgeNGramTokenizer(LuceneVersion version, AttributeFactory factor
private void Init(LuceneVersion version, Side side, int minGram, int maxGram)
{
- //if (version == null)
- //{
- // throw new ArgumentException("version must not be null");
- //}
+ // LUCENENET specific - version cannot be null because it is a value type.
- if (!Enum.IsDefined(typeof(Side), side))
+ if (!side.IsDefined())
{
- throw new ArgumentException("sideLabel must be either front or back");
+ throw new ArgumentOutOfRangeException(nameof(side), "sideLabel must be either front or back"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minGram < 1)
{
- throw new ArgumentException("minGram must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(minGram), "minGram must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minGram > maxGram)
@@ -295,4 +292,17 @@ public override void Reset()
started = false;
}
}
+
+ // LUCENENET: added this to avoid the Enum.IsDefined() method, which requires boxing
+ internal static partial class SideExtensions
+ {
+#pragma warning disable CS0612 // Type or member is obsolete
+ internal static bool IsDefined(this Lucene43EdgeNGramTokenizer.Side side)
+ {
+ return side >= Lucene43EdgeNGramTokenizer.Side.FRONT &&
+ side <= Lucene43EdgeNGramTokenizer.Side.BACK;
+ }
+#pragma warning restore CS0612 // Type or member is obsolete
+
+ }
}
\ No newline at end of file
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/NGram/Lucene43NGramTokenizer.cs b/src/Lucene.Net.Analysis.Common/Analysis/NGram/Lucene43NGramTokenizer.cs
index ae31bd32ab..2c10821d80 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/NGram/Lucene43NGramTokenizer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/NGram/Lucene43NGramTokenizer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -77,7 +77,7 @@ private void Init(int minGram, int maxGram)
{
if (minGram < 1)
{
- throw new ArgumentException("minGram must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(minGram), "minGram must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minGram > maxGram)
{
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/NGram/NGramTokenFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/NGram/NGramTokenFilter.cs
index b1b76cbeb9..7f6c2015d8 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/NGram/NGramTokenFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/NGram/NGramTokenFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
@@ -90,7 +90,7 @@ public NGramTokenFilter(LuceneVersion version, TokenStream input, int minGram, i
CharacterUtils.GetInstance(version) : CharacterUtils.GetJava4Instance(version);
if (minGram < 1)
{
- throw new ArgumentException("minGram must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(minGram), "minGram must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minGram > maxGram)
{
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/NGram/NGramTokenizer.cs b/src/Lucene.Net.Analysis.Common/Analysis/NGram/NGramTokenizer.cs
index c3f1deb76f..36cc3893a5 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/NGram/NGramTokenizer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/NGram/NGramTokenizer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
@@ -185,7 +185,7 @@ private void Init(LuceneVersion version, int minGram, int maxGram, bool edgesOnl
CharacterUtils.GetInstance(version) : CharacterUtils.GetJava4Instance(version);
if (minGram < 1)
{
- throw new ArgumentException("minGram must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(minGram), "minGram must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minGram > maxGram)
{
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Nl/DutchAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Nl/DutchAnalyzer.cs
index ad02830f82..f6c8224fc9 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Nl/DutchAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Nl/DutchAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -81,11 +81,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
@@ -183,9 +183,9 @@ public DutchAnalyzer(LuceneVersion matchVersion, CharArraySet stopwords, CharArr
{
this.stemdict = builder.Build();
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
- throw new Exception("can not build stem dict", ex);
+ throw RuntimeException.Create("can not build stem dict", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/No/NorwegianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/No/NorwegianAnalyzer.cs
index 90197343e6..a84bfe97ac 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/No/NorwegianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/No/NorwegianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -63,11 +63,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Path/PathHierarchyTokenizer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Path/PathHierarchyTokenizer.cs
index c45cba8eeb..f84078e6f7 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Path/PathHierarchyTokenizer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Path/PathHierarchyTokenizer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -83,11 +83,11 @@ public PathHierarchyTokenizer(AttributeFactory factory, TextReader input, int bu
{
if (bufferSize < 0)
{
- throw new ArgumentException("bufferSize cannot be negative");
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), "bufferSize cannot be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (skip < 0)
{
- throw new ArgumentException("skip cannot be negative");
+ throw new ArgumentOutOfRangeException(nameof(skip), "skip cannot be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
offsetAtt = AddAttribute();
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Path/ReversePathHierarchyTokenizer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Path/ReversePathHierarchyTokenizer.cs
index 2600949587..7f32944c42 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Path/ReversePathHierarchyTokenizer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Path/ReversePathHierarchyTokenizer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.Collections.Generic;
@@ -96,11 +96,11 @@ public ReversePathHierarchyTokenizer(AttributeFactory factory, TextReader input,
{
if (bufferSize < 0)
{
- throw new ArgumentException("bufferSize cannot be negative");
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), "bufferSize cannot be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (skip < 0)
{
- throw new ArgumentException("skip cannot be negative");
+ throw new ArgumentOutOfRangeException(nameof(skip), "skip cannot be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
termAtt = AddAttribute();
offsetAtt = AddAttribute();
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Payloads/NumericPayloadTokenFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Payloads/NumericPayloadTokenFilter.cs
index 1e0bd3dfc5..88ca5fc559 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Payloads/NumericPayloadTokenFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Payloads/NumericPayloadTokenFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;
using System;
@@ -38,7 +38,7 @@ public NumericPayloadTokenFilter(TokenStream input, float payload, string typeMa
{
if (typeMatch == null)
{
- throw new ArgumentException("typeMatch cannot be null");
+ throw new ArgumentNullException(nameof(typeMatch), "typeMatch cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
//Need to encode the payload
thePayload = new BytesRef(PayloadHelper.EncodeSingle(payload));
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Position/PositionFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Position/PositionFilter.cs
index e3891162a2..f0bae0e10f 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Position/PositionFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Position/PositionFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using System;
using Lucene.Net.Analysis.TokenAttributes;
@@ -66,7 +66,7 @@ public PositionFilter(TokenStream input, int positionIncrement)
{
if (positionIncrement < 0)
{
- throw new ArgumentException("positionIncrement may not be negative");
+ throw new ArgumentOutOfRangeException(nameof(positionIncrement), "positionIncrement may not be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.positionIncrement = positionIncrement;
posIncrAtt = AddAttribute();
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Pt/PortugueseAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Pt/PortugueseAnalyzer.cs
index cde1ec8fba..be3fb3f8ad 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Pt/PortugueseAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Pt/PortugueseAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -68,11 +68,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Pt/RSLPStemmerBase.cs b/src/Lucene.Net.Analysis.Common/Analysis/Pt/RSLPStemmerBase.cs
index 8d6f5bb1ba..72d12d988b 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Pt/RSLPStemmerBase.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Pt/RSLPStemmerBase.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N.Collections.Generic.Extensions;
using J2N.Text;
using Lucene.Net.Analysis.Util;
@@ -133,7 +133,7 @@ public RuleWithSetExceptions(string suffix, int min, string replacement, string[
{
if (!exceptions[i].EndsWith(suffix, StringComparison.Ordinal))
{
- throw new Exception("useless exception '" + exceptions[i] + "' does not end with '" + suffix + "'");
+ throw RuntimeException.Create("useless exception '" + exceptions[i] + "' does not end with '" + suffix + "'");
}
}
this.m_exceptions = new CharArraySet(
@@ -163,7 +163,7 @@ public RuleWithSuffixExceptions(string suffix, int min, string replacement, stri
{
if (!exceptions[i].EndsWith(suffix, StringComparison.Ordinal))
{
- throw new Exception("warning: useless exception '" + exceptions[i] + "' does not end with '" + suffix + "'");
+ throw RuntimeException.Create("warning: useless exception '" + exceptions[i] + "' does not end with '" + suffix + "'");
}
}
this.m_exceptions = new char[exceptions.Length][];
@@ -280,18 +280,25 @@ public virtual int Apply(char[] s, int len)
/// a Map containing the named s in this description.
protected static IDictionary Parse(Type clazz, string resource)
{
- IDictionary steps = new Dictionary();
-
- using (TextReader r = IOUtils.GetDecodingReader(clazz, resource, Encoding.UTF8))
+ try
{
- string step;
- while ((step = ReadLine(r)) != null)
+ IDictionary steps = new Dictionary();
+
+ using (TextReader r = IOUtils.GetDecodingReader(clazz, resource, Encoding.UTF8))
{
- Step s = ParseStep(r, step);
- steps[s.m_name] = s;
+ string step;
+ while ((step = ReadLine(r)) != null)
+ {
+ Step s = ParseStep(r, step);
+ steps[s.m_name] = s;
+ }
}
+ return steps;
+ }
+ catch (Exception e) when (e.IsIOException())
+ {
+ throw RuntimeException.Create(e);
}
- return steps;
}
private static readonly Regex headerPattern = new Regex("^\\{\\s*\"([^\"]*)\",\\s*([0-9]+),\\s*(0|1),\\s*\\{(.*)\\},\\s*$", RegexOptions.Compiled);
@@ -304,7 +311,7 @@ private static Step ParseStep(TextReader r, string header)
Match matcher = headerPattern.Match(header);
if (!matcher.Success)
{
- throw new Exception("Illegal Step header specified at line " /*+ r.LineNumber*/); // TODO Line number
+ throw RuntimeException.Create("Illegal Step header specified at line " /*+ r.LineNumber*/); // TODO Line number
}
//if (Debugging.AssertsEnabled) Debugging.Assert(headerPattern.GetGroupNumbers().Length == 4); // Not possible to read the number of groups that matched in .NET
string name = matcher.Groups[1].Value;
@@ -349,7 +356,7 @@ private static Rule[] ParseRules(TextReader r, int type)
}
else
{
- throw new Exception("Illegal Step rule specified at line " /*+ r.LineNumber*/);
+ throw RuntimeException.Create("Illegal Step rule specified at line " /*+ r.LineNumber*/);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Ro/RomanianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Ro/RomanianAnalyzer.cs
index bb4b1b7141..a4a5f4403c 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Ro/RomanianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Ro/RomanianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -63,11 +63,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(RomanianAnalyzer), DEFAULT_STOPWORD_FILE, STOPWORDS_COMMENT);
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Ru/RussianAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Ru/RussianAnalyzer.cs
index 836e46b2b5..03ba174dbe 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Ru/RussianAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Ru/RussianAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -83,11 +83,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleAnalyzerWrapper.cs b/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleAnalyzerWrapper.cs
index d0f33cff7b..a499d671a9 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleAnalyzerWrapper.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleAnalyzerWrapper.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Util;
using System;
@@ -76,17 +76,17 @@ public ShingleAnalyzerWrapper(Analyzer @delegate, int minShingleSize, int maxShi
if (maxShingleSize < 2)
{
- throw new ArgumentOutOfRangeException("Max shingle size must be >= 2");
+ throw new ArgumentOutOfRangeException(nameof(maxShingleSize), "Max shingle size must be >= 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.maxShingleSize = maxShingleSize;
if (minShingleSize < 2)
{
- throw new ArgumentOutOfRangeException("Min shingle size must be >= 2");
+ throw new ArgumentOutOfRangeException(nameof(minShingleSize), "Min shingle size must be >= 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minShingleSize > maxShingleSize)
{
- throw new ArgumentOutOfRangeException("Min shingle size must be <= max shingle size");
+ throw new ArgumentException("Min shingle size must be <= max shingle size");
}
this.minShingleSize = minShingleSize;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleFilter.cs
index 8f1310d741..75ff327285 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Support;
using Lucene.Net.Util;
@@ -262,7 +262,7 @@ public void SetMaxShingleSize(int maxShingleSize)
{
if (maxShingleSize < 2)
{
- throw new ArgumentException("Max shingle size must be >= 2");
+ throw new ArgumentOutOfRangeException(nameof(maxShingleSize), "Max shingle size must be >= 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.maxShingleSize = maxShingleSize;
}
@@ -283,7 +283,7 @@ public void SetMinShingleSize(int minShingleSize)
{
if (minShingleSize < 2)
{
- throw new ArgumentException("Min shingle size must be >= 2");
+ throw new ArgumentOutOfRangeException(nameof(minShingleSize), "Min shingle size must be >= 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minShingleSize > maxShingleSize)
{
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleFilterFactory.cs b/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleFilterFactory.cs
index b5f06eb393..75b5529b94 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Shingle/ShingleFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using System;
using System.Collections.Generic;
@@ -50,16 +50,16 @@ public ShingleFilterFactory(IDictionary args)
maxShingleSize = GetInt32(args, "maxShingleSize", ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE);
if (maxShingleSize < 2)
{
- throw new ArgumentOutOfRangeException("Invalid maxShingleSize (" + maxShingleSize + ") - must be at least 2");
+ throw new ArgumentOutOfRangeException(nameof(maxShingleSize), "Invalid maxShingleSize (" + maxShingleSize + ") - must be at least 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
minShingleSize = GetInt32(args, "minShingleSize", ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE);
if (minShingleSize < 2)
{
- throw new ArgumentOutOfRangeException("Invalid minShingleSize (" + minShingleSize + ") - must be at least 2");
+ throw new ArgumentOutOfRangeException(nameof(minShingleSize), "Invalid minShingleSize (" + minShingleSize + ") - must be at least 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minShingleSize > maxShingleSize)
{
- throw new ArgumentOutOfRangeException("Invalid minShingleSize (" + minShingleSize + ") - must be no greater than maxShingleSize (" + maxShingleSize + ")");
+ throw new ArgumentException("Invalid minShingleSize (" + minShingleSize + ") - must be no greater than maxShingleSize (" + maxShingleSize + ")");
}
outputUnigrams = GetBoolean(args, "outputUnigrams", true);
outputUnigramsIfNoShingles = GetBoolean(args, "outputUnigramsIfNoShingles", false);
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Sinks/DateRecognizerSinkFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Sinks/DateRecognizerSinkFilter.cs
index bdc2328f87..d8babea675 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Sinks/DateRecognizerSinkFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Sinks/DateRecognizerSinkFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;
using System;
@@ -144,14 +144,14 @@ public override bool Accept(AttributeSource source)
m_termAtt = source.AddAttribute();
}
- DateTime date; //We don't care about the date, just that we can parse it as a date
+ //We don't care about the date, just that we can parse it as a date
if (m_formats == null)
{
- return DateTime.TryParse(m_termAtt.ToString(), m_culture, m_style, out date);
+ return DateTime.TryParse(m_termAtt.ToString(), m_culture, m_style, out _);
}
else
{
- return DateTime.TryParseExact(m_termAtt.ToString(), m_formats, m_culture, m_style, out date);
+ return DateTime.TryParseExact(m_termAtt.ToString(), m_formats, m_culture, m_style, out _);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Sinks/TeeSinkTokenFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Sinks/TeeSinkTokenFilter.cs
index 89ad4e6e22..678df888cb 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Sinks/TeeSinkTokenFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Sinks/TeeSinkTokenFilter.cs
@@ -220,7 +220,7 @@ internal void AddState(AttributeSource.State state)
{
if (it != null)
{
- throw new InvalidOperationException("The tee must be consumed before sinks are consumed.");
+ throw IllegalStateException.Create("The tee must be consumed before sinks are consumed.");
}
cachedStates.Add(state);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Sinks/TokenRangeSinkFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Sinks/TokenRangeSinkFilter.cs
index a62ebdbb69..c2b04667c3 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Sinks/TokenRangeSinkFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Sinks/TokenRangeSinkFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Util;
using System;
@@ -34,11 +34,11 @@ public TokenRangeSinkFilter(int lower, int upper)
{
if (lower < 1)
{
- throw new ArgumentOutOfRangeException("lower must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(lower), "lower must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (lower > upper)
{
- throw new ArgumentOutOfRangeException("lower must not be greater than upper");
+ throw new ArgumentException("lower must not be greater than upper");
}
this.lower = lower;
this.upper = upper;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Snowball/SnowballFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Snowball/SnowballFilter.cs
index c27635a088..f0df84c79e 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Snowball/SnowballFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Snowball/SnowballFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Tartarus.Snowball;
using System;
@@ -79,7 +79,7 @@ public SnowballFilter(TokenStream @in, string name)
stemmer = (SnowballProgram)Activator.CreateInstance(stemClass);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
throw new ArgumentException("Invalid stemmer class specified: " + name, e);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Snowball/SnowballPorterFilterFactory.cs b/src/Lucene.Net.Analysis.Common/Analysis/Snowball/SnowballPorterFilterFactory.cs
index e822d70b33..74a7fc6398 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Snowball/SnowballPorterFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Snowball/SnowballPorterFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Tartarus.Snowball;
@@ -78,9 +78,9 @@ public override TokenStream Create(TokenStream input)
{
program = (SnowballProgram)Activator.CreateInstance(stemClass);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception("Error instantiating stemmer for language " + language + "from class " + stemClass, e);
+ throw RuntimeException.Create("Error instantiating stemmer for language " + language + "from class " + stemClass, e);
}
if (protectedWords != null)
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/ClassicTokenizer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/ClassicTokenizer.cs
index 2f09695ced..5e8d983976 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/ClassicTokenizer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/ClassicTokenizer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;
using System;
@@ -91,7 +91,7 @@ public int MaxTokenLength
set
{
if (value < 1)
- throw new ArgumentException("maxTokenLength must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(MaxTokenLength), "maxTokenLength must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
this.maxTokenLength = value;
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/ClassicTokenizerImpl.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/ClassicTokenizerImpl.cs
index 6a2deb995f..57cd51ddcc 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/ClassicTokenizerImpl.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/ClassicTokenizerImpl.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
/* The following code was generated by JFlex 1.5.1 */
using System;
using System.IO;
@@ -604,16 +604,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/StandardTokenizerImpl.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/StandardTokenizerImpl.cs
index af84bec07e..1cb3cc6e31 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/StandardTokenizerImpl.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/StandardTokenizerImpl.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
// The following code was generated by JFlex 1.5.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
@@ -1201,16 +1201,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std31/StandardTokenizerImpl31.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std31/StandardTokenizerImpl31.cs
index 8e9afc4fe9..287524a5df 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std31/StandardTokenizerImpl31.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std31/StandardTokenizerImpl31.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -915,16 +915,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
///
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std31/UAX29URLEmailTokenizerImpl31.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std31/UAX29URLEmailTokenizerImpl31.cs
index afded04780..6cbdc6d6d6 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std31/UAX29URLEmailTokenizerImpl31.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std31/UAX29URLEmailTokenizerImpl31.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -3470,16 +3470,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
///
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std34/StandardTokenizerImpl34.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std34/StandardTokenizerImpl34.cs
index 487571e24f..0c4a615622 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std34/StandardTokenizerImpl34.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std34/StandardTokenizerImpl34.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -934,16 +934,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
///
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std34/UAX29URLEmailTokenizerImpl34.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std34/UAX29URLEmailTokenizerImpl34.cs
index 9ca63765c4..7f69ca3b67 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std34/UAX29URLEmailTokenizerImpl34.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std34/UAX29URLEmailTokenizerImpl34.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -3584,16 +3584,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
///
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std36/UAX29URLEmailTokenizerImpl36.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std36/UAX29URLEmailTokenizerImpl36.cs
index 6a854f64be..24629bf58e 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std36/UAX29URLEmailTokenizerImpl36.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std36/UAX29URLEmailTokenizerImpl36.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -4021,16 +4021,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std40/StandardTokenizerImpl40.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std40/StandardTokenizerImpl40.cs
index 1665c1a5c4..d2c1c9a8e2 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std40/StandardTokenizerImpl40.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std40/StandardTokenizerImpl40.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -1051,16 +1051,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std40/UAX29URLEmailTokenizerImpl40.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std40/UAX29URLEmailTokenizerImpl40.cs
index 687dca7a92..729302a174 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std40/UAX29URLEmailTokenizerImpl40.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/Std40/UAX29URLEmailTokenizerImpl40.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -4239,16 +4239,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/UAX29URLEmailTokenizer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/UAX29URLEmailTokenizer.cs
index c7b0bde587..efb952f336 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/UAX29URLEmailTokenizer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/UAX29URLEmailTokenizer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Standard.Std31;
using Lucene.Net.Analysis.Standard.Std34;
using Lucene.Net.Analysis.Standard.Std36;
@@ -98,7 +98,7 @@ public int MaxTokenLength
{
if (value < 1)
{
- throw new ArgumentException("maxTokenLength must be greater than zero");
+ throw new ArgumentOutOfRangeException(nameof(MaxTokenLength), "maxTokenLength must be greater than zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.maxTokenLength = value;
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Standard/UAX29URLEmailTokenizerImpl.cs b/src/Lucene.Net.Analysis.Common/Analysis/Standard/UAX29URLEmailTokenizerImpl.cs
index c4ab7b7eb4..08a780c26f 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Standard/UAX29URLEmailTokenizerImpl.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Standard/UAX29URLEmailTokenizerImpl.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -9346,16 +9346,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Sv/SwedishAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Sv/SwedishAnalyzer.cs
index ce59fa313a..716b9e8f59 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Sv/SwedishAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Sv/SwedishAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -63,11 +63,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/FSTSynonymFilterFactory.cs b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/FSTSynonymFilterFactory.cs
index dff8b69d5f..9aa8336270 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/FSTSynonymFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/FSTSynonymFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
@@ -105,7 +105,7 @@ public void Inform(IResourceLoader loader)
// TODO: expose dedup as a parameter?
map = LoadSynonyms(loader, formatClass, true, analyzer);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsParseException())
{
throw new IOException("Error parsing synonyms file:", e);
}
@@ -124,7 +124,7 @@ private SynonymMap LoadSynonyms(IResourceLoader loader, string cname, bool dedup
{
parser = (SynonymMap.Parser)Activator.CreateInstance(clazz, new object[] { dedup, expand, analyzer });
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
@@ -158,7 +158,7 @@ private TokenizerFactory LoadTokenizerFactory(IResourceLoader loader, string cna
}
return tokFactory;
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SlowSynonymFilterFactory.cs b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SlowSynonymFilterFactory.cs
index 20ba7119fa..9954d3ba7a 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SlowSynonymFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SlowSynonymFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
using System;
@@ -221,7 +221,7 @@ private TokenizerFactory LoadTokenizerFactory(IResourceLoader loader, string cna
}
return tokFactory;
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsException())
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SolrSynonymParser.cs b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SolrSynonymParser.cs
index 59236dd458..7b6807d327 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SolrSynonymParser.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SolrSynonymParser.cs
@@ -1,4 +1,5 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
+using J2N.Text;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
@@ -134,9 +135,9 @@ public override void Parse(TextReader @in)
}
}
}
- catch (ArgumentException e)
+ catch (Exception e) when (e.IsIllegalArgumentException())
{
- throw new Exception("Invalid synonym rule at line " + lineNumber, e);
+ throw new ParseException("Invalid synonym rule at line " + lineNumber, 0, e);
//ex.initCause(e);
//throw ex;
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SynonymFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SynonymFilter.cs
index 18ef911659..3884235a58 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SynonymFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SynonymFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N;
using J2N.Numerics;
using Lucene.Net.Analysis.TokenAttributes;
@@ -271,9 +271,9 @@ public SynonymFilter(TokenStream input, SynonymMap synonyms, bool ignoreCase)
this.synonyms = synonyms;
this.ignoreCase = ignoreCase;
this.fst = synonyms.Fst;
- if (fst == null)
+ if (fst is null)
{
- throw new ArgumentException("fst must be non-null");
+ throw new ArgumentNullException(nameof(synonyms.Fst), "fst must be non-null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
this.fstReader = fst.GetBytesReader();
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SynonymMap.cs b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SynonymMap.cs
index d79074aa44..6cbb5112b1 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SynonymMap.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/SynonymMap.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Diagnostics;
using Lucene.Net.Store;
@@ -6,7 +6,6 @@
using Lucene.Net.Util.Fst;
using System;
using System.Collections.Generic;
-using System.Diagnostics;
using System.IO;
using JCG = J2N.Collections.Generic;
@@ -159,19 +158,19 @@ internal virtual void Add(CharsRef input, int numInputWords, CharsRef output, in
// first convert to UTF-8
if (numInputWords <= 0)
{
- throw new ArgumentException("numInputWords must be > 0 (got " + numInputWords + ")");
+ throw new ArgumentOutOfRangeException(nameof(numInputWords), "numInputWords must be > 0 (got " + numInputWords + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (input.Length <= 0)
{
- throw new ArgumentException("input.length must be > 0 (got " + input.Length + ")");
+ throw new ArgumentOutOfRangeException(nameof(input.Length), "input.Length must be > 0 (got " + input.Length + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (numOutputWords <= 0)
{
- throw new ArgumentException("numOutputWords must be > 0 (got " + numOutputWords + ")");
+ throw new ArgumentOutOfRangeException(nameof(numOutputWords), "numOutputWords must be > 0 (got " + numOutputWords + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (output.Length <= 0)
{
- throw new ArgumentException("output.length must be > 0 (got " + output.Length + ")");
+ throw new ArgumentOutOfRangeException(nameof(output.Length), "output.Length must be > 0 (got " + output.Length + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (Debugging.AssertsEnabled)
@@ -357,9 +356,7 @@ public Parser(bool dedup, Analyzer analyzer)
///
public virtual CharsRef Analyze(string text, CharsRef reuse)
{
- IOException priorException = null;
- TokenStream ts = analyzer.GetTokenStream("", text);
- try
+ using (TokenStream ts = analyzer.GetTokenStream("", text))
{
var termAtt = ts.AddAttribute();
var posIncAtt = ts.AddAttribute();
@@ -388,14 +385,6 @@ public virtual CharsRef Analyze(string text, CharsRef reuse)
}
ts.End();
}
- catch (IOException e)
- {
- priorException = e;
- }
- finally
- {
- IOUtils.DisposeWhileHandlingException(priorException, ts);
- }
if (reuse.Length == 0)
{
throw new ArgumentException("term: " + text + " was completely eliminated by analyzer");
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/WordnetSynonymParser.cs b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/WordnetSynonymParser.cs
index ea02d11459..c79333c3de 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Synonym/WordnetSynonymParser.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Synonym/WordnetSynonymParser.cs
@@ -1,4 +1,5 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
+using J2N.Text;
using Lucene.Net.Util;
using System;
using System.IO;
@@ -78,9 +79,9 @@ public override void Parse(TextReader @in)
// final synset in the file
AddInternal(synset, synsetSize);
}
- catch (ArgumentException e)
+ catch (Exception e) when (e.IsIllegalArgumentException())
{
- throw new Exception("Invalid synonym rule at line " + lineNumber.ToString(), e);
+ throw new ParseException("Invalid synonym rule at line " + lineNumber, lineNumber, e);
}
finally
{
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Th/ThaiAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Th/ThaiAnalyzer.cs
index 64d5278234..c66452e478 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Th/ThaiAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Th/ThaiAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
#if FEATURE_BREAKITERATOR
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Standard;
@@ -65,11 +65,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(ThaiAnalyzer), DEFAULT_STOPWORD_FILE, STOPWORDS_COMMENT);
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Tr/TurkishAnalyzer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Tr/TurkishAnalyzer.cs
index de7e0615c4..9e5b804fb0 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Tr/TurkishAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Tr/TurkishAnalyzer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Snowball;
@@ -63,11 +63,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(false, typeof(TurkishAnalyzer), DEFAULT_STOPWORD_FILE, STOPWORDS_COMMENT);
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Util/AnalysisSPILoader.cs b/src/Lucene.Net.Analysis.Common/Analysis/Util/AnalysisSPILoader.cs
index f109cddd0e..3d4224b548 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Util/AnalysisSPILoader.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Util/AnalysisSPILoader.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Support;
using Lucene.Net.Util;
@@ -80,14 +80,14 @@ public void Reload()
if (name == null)
{
- throw new InvalidOperationException("The class name " + service.Name +
+ throw ServiceConfigurationError.Create("The class name " + service.Name +
" has wrong suffix, allowed are: " + Arrays.ToString(suffixes));
}
// only add the first one for each name, later services will be ignored
// this allows to place services before others in classpath to make
// them used instead of others
//
- // LUCENETODO: Should we disallow duplicate names here?
+ // TODO: Should we disallow duplicate names here?
// Allowing it may get confusing on collisions, as different packages
// could contain same factory class, which is a naming bug!
// When changing this be careful to allow reload()!
@@ -107,7 +107,7 @@ public S NewInstance(string name, IDictionary args)
{
return (S)Activator.CreateInstance(service, new object[] { args });
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
throw new ArgumentException("SPI class of type " + clazz.Name + " with name '" + name + "' cannot be instantiated. " +
"This is likely due to a missing reference of the .NET Assembly containing the class '" + service.Name + "' in your project or AppDomain: ", e);
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Util/BufferedCharFilter.cs b/src/Lucene.Net.Analysis.Common/Analysis/Util/BufferedCharFilter.cs
index bcb394d4ee..4d6a86e7f9 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Util/BufferedCharFilter.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Util/BufferedCharFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
// This class was sourced from the Apache Harmony project's BufferedReader
// https://svn.apache.org/repos/asf/harmony/enhanced/java/trunk/
@@ -99,7 +99,7 @@ public BufferedCharFilter(TextReader @in, int size)
{
if (size <= 0)
{
- throw new ArgumentOutOfRangeException("Buffer size <= 0");
+ throw new ArgumentOutOfRangeException(nameof(size), "Buffer size <= 0");
}
this.@in = @in;
buf = new char[size];
@@ -223,7 +223,7 @@ public override void Mark(int markLimit)
{
if (markLimit < 0)
{
- throw new ArgumentOutOfRangeException("Read-ahead limit < 0");
+ throw new ArgumentOutOfRangeException(nameof(markLimit), "Read-ahead limit < 0");
}
lock (m_lock)
{
@@ -289,10 +289,18 @@ public override int Read(char[] buffer, int offset, int length)
lock(m_lock)
{
EnsureOpen();
- if (offset < 0 || offset > buffer.Length - length || length < 0)
- {
- throw new ArgumentOutOfRangeException();
- }
+ // LUCENENT specific - refactored guard clauses to throw individual messages.
+ // Note that this is the order the Apache Harmony tests expect it to be checked in.
+ if (offset < 0)
+ throw new ArgumentOutOfRangeException(nameof(offset), offset, $"{nameof(offset)} must not be negative.");
+ // LUCENENET specific - Added guard clause for null
+ if (buffer is null)
+ throw new ArgumentNullException(nameof(buffer));
+ if (offset > buffer.Length - length)
+ throw new ArgumentOutOfRangeException(nameof(offset) + " + " + nameof(length), $"offset + length may not be greater than the size of {nameof(buffer)}");
+ if (length < 0)
+ throw new ArgumentOutOfRangeException(nameof(length), length, $"{nameof(length)} must not be negative.");
+
int outstanding = length;
while (outstanding > 0)
{
@@ -500,6 +508,7 @@ public override void Reset()
EnsureOpen();
if (mark < 0)
{
+ // LUCENENET NOTE: Seems odd, but in .NET StreamReader, this is also the exception that is thrown when closed.
throw new IOException("Reader not marked");
}
pos = mark;
@@ -523,7 +532,7 @@ public override long Skip(int amount)
{
if (amount < 0L)
{
- throw new ArgumentOutOfRangeException("skip value is negative");
+ throw new ArgumentOutOfRangeException(nameof(amount), "skip value is negative");
}
lock (m_lock)
{
@@ -607,7 +616,7 @@ public override void Close()
{
if (!isDisposing)
{
- throw new NotSupportedException("Close() is not supported. Call Dispose() instead.");
+ throw UnsupportedOperationException.Create("Close() is not supported. Call Dispose() instead.");
}
}
#endif
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Util/CharArrayMap.cs b/src/Lucene.Net.Analysis.Common/Analysis/Util/CharArrayMap.cs
index 15cb538f93..21559e6111 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Util/CharArrayMap.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Util/CharArrayMap.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N;
using J2N.Globalization;
using J2N.Text;
@@ -202,9 +202,9 @@ public virtual void Clear()
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
- public virtual bool Contains(KeyValuePair item)
+ public virtual bool Contains(KeyValuePair item) // LUCENENET TODO: API - rather than marking this DesignerSerializationVisibility.Hidden, it would be better to make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -281,9 +281,9 @@ public virtual bool ContainsKey(ICharSequence text)
///
public virtual bool ContainsKey(object o)
{
- if (o == null)
+ if (o is null)
{
- throw new ArgumentException("o can't be null", nameof(o));
+ throw new ArgumentNullException(nameof(o), "o can't be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
var c = o as char[];
@@ -797,9 +797,9 @@ public override int GetHashCode()
private int GetHashCode(char[] text, int offset, int length)
{
- if (text == null)
+ if (text is null)
{
- throw new ArgumentException("text can't be null", nameof(text));
+ throw new ArgumentNullException(nameof(text), "text can't be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
int code = 0;
int stop = offset + length;
@@ -824,9 +824,9 @@ private int GetHashCode(char[] text, int offset, int length)
private int GetHashCode(ICharSequence text)
{
- if (text == null)
+ if (text is null)
{
- throw new ArgumentException("text can't be null", nameof(text));
+ throw new ArgumentNullException(nameof(text), "text can't be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
int code = 0;
@@ -852,9 +852,9 @@ private int GetHashCode(ICharSequence text)
private int GetHashCode(string text)
{
- if (text == null)
+ if (text is null)
{
- throw new ArgumentException("text can't be null", nameof(text));
+ throw new ArgumentNullException(nameof(text), "text can't be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
int code = 0;
@@ -1124,9 +1124,9 @@ public KeyCollection(CharArrayMap outerInstance)
public bool IsReadOnly => outerInstance.IsReadOnly;
- public void Add(string item)
+ public void Add(string item) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public void Clear()
@@ -1153,9 +1153,9 @@ public IEnumerator GetEnumerator()
return new KeyEnumerator(outerInstance);
}
- public bool Remove(string item)
+ public bool Remove(string item) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
IEnumerator IEnumerable.GetEnumerator()
@@ -1212,9 +1212,9 @@ public ValueCollection(CharArrayMap outerInstance)
public bool IsReadOnly => outerInstance.IsReadOnly;
- public void Add(TValue item)
+ public void Add(TValue item) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public void Clear()
@@ -1233,9 +1233,9 @@ public bool Contains(TValue item)
return false;
}
- public void CopyTo(TValue[] array, int arrayIndex)
+ public void CopyTo(TValue[] array, int arrayIndex) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public IEnumerator GetEnumerator()
@@ -1243,9 +1243,9 @@ public IEnumerator GetEnumerator()
return new ValueEnumerator(outerInstance);
}
- public bool Remove(TValue item)
+ public bool Remove(TValue item) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
IEnumerator IEnumerable.GetEnumerator()
@@ -1335,17 +1335,17 @@ IEnumerator IEnumerable.GetEnumerator()
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
- public virtual bool Remove(string key)
+ public virtual bool Remove(string key) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
- public virtual bool Remove(KeyValuePair item)
+ public virtual bool Remove(KeyValuePair item) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -1440,21 +1440,21 @@ internal UnmodifiableCharArraySet(ICharArrayMap map)
{
}
- public override bool Add(object o)
+ public override bool Add(object o) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
- public override bool Add(ICharSequence text)
+ public override bool Add(ICharSequence text) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
- public override bool Add(string text)
+ public override bool Add(string text) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
- public override bool Add(char[] text)
+ public override bool Add(char[] text) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
@@ -1524,7 +1524,7 @@ public virtual TValue SetValue(TValue value)
{
if (!allowModify)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
TValue old = outerInstance.values[lastPos].Value;
outerInstance.values[lastPos].Value = value;
@@ -1630,9 +1630,9 @@ public bool Contains(object o)
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
- public bool Remove(KeyValuePair item)
+ public bool Remove(KeyValuePair item) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public int Count => outerInstance.count;
@@ -1641,7 +1641,7 @@ public void Clear()
{
if (!allowModify)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
outerInstance.Clear();
}
@@ -1792,9 +1792,9 @@ internal static CharArrayMap Copy(LuceneVersion matchVersion, IC
/// if the given map is null.
public static CharArrayMap UnmodifiableMap(CharArrayMap map) // LUCENENET TODO: API - Rename AsReadOnly() to match .NET convention
{
- if (map == null)
+ if (map is null)
{
- throw new ArgumentException("Given map is null", nameof(map));
+ throw new ArgumentNullException(nameof(map), "Given map is null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (map == CharArrayMap.EmptyMap() || map.Count == 0)
{
@@ -1813,9 +1813,9 @@ public static CharArrayMap UnmodifiableMap(CharArrayMap
///
internal static ICharArrayMap UnmodifiableMap(ICharArrayMap map)
{
- if (map == null)
+ if (map is null)
{
- throw new ArgumentException("Given map is null", nameof(map));
+ throw new ArgumentNullException(nameof(map), "Given map is null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (map == CharArrayMap.EmptyMap() || map.Count == 0)
{
@@ -1841,47 +1841,47 @@ public UnmodifiableCharArrayMap(ICharArrayMap map)
public override void Clear()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override TValue Put(char[] text, TValue val)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override TValue Put(ICharSequence text, TValue val)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override TValue Put(string text, TValue val)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override TValue Put(object o, TValue val)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override bool Put(char[] text)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override bool Put(ICharSequence text)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override bool Put(string text)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override bool Put(object o)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
[Obsolete("Not applicable in this class.")]
@@ -1889,7 +1889,7 @@ public override bool Put(object o)
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override bool Remove(string key)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
internal override EntrySet_ CreateEntrySet()
@@ -1900,36 +1900,36 @@ internal override EntrySet_ CreateEntrySet()
#region Added for better .NET support LUCENENET
public override void Add(string key, TValue value)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override void Add(KeyValuePair item)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override TValue this[char[] key, int offset, int length]
{
get => base[key, offset, length];
- set => throw new NotSupportedException();
+ set => throw UnsupportedOperationException.Create();
}
public override TValue this[char[] key]
{
get => base[key];
- set => throw new NotSupportedException();
+ set => throw UnsupportedOperationException.Create();
}
public override TValue this[ICharSequence key]
{
get => base[key];
- set => throw new NotSupportedException();
+ set => throw UnsupportedOperationException.Create();
}
public override TValue this[string key]
{
get => base[key];
- set => throw new NotSupportedException();
+ set => throw UnsupportedOperationException.Create();
}
public override TValue this[object key]
{
get => base[key];
- set => throw new NotSupportedException();
+ set => throw UnsupportedOperationException.Create();
}
[Obsolete("Not applicable in this class.")]
@@ -1937,7 +1937,7 @@ public override TValue this[object key]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override bool Remove(KeyValuePair item)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
#endregion
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Util/CharArraySet.cs b/src/Lucene.Net.Analysis.Common/Analysis/Util/CharArraySet.cs
index bdb8211afb..030c8cc747 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Util/CharArraySet.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Util/CharArraySet.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N.Globalization;
using J2N.Text;
using Lucene.Net.Util;
@@ -227,11 +227,11 @@ void ICollection.Add(string item)
/// an new unmodifiable .
///
/// if the given set is null.
- public static CharArraySet UnmodifiableSet(CharArraySet set)
+ public static CharArraySet UnmodifiableSet(CharArraySet set) // LUCENENET TODO: API - Rename AsReadOnly() to match .NET convention
{
- if (set == null)
+ if (set is null)
{
- throw new ArgumentNullException("Given set is null");
+ throw new ArgumentNullException(nameof(set), "Given set is null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (set == EMPTY_SET)
{
@@ -380,10 +380,10 @@ public void CopyTo(string[] array, int arrayIndex)
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
- public virtual bool Remove(string item)
+ public virtual bool Remove(string item) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
// LUCENENET NOTE: According to the documentation header, Remove should not be supported
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
// LUCENENET - Added to ensure equality checking works in tests
@@ -417,7 +417,7 @@ public virtual bool UnionWith(IEnumerable other)
}
if (IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -444,7 +444,7 @@ public virtual bool UnionWith(IEnumerable other)
}
if (IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -470,7 +470,7 @@ public virtual void UnionWith(IEnumerable other)
}
if (IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
foreach (var item in other)
{
@@ -492,7 +492,7 @@ public virtual bool UnionWith(IEnumerable other)
}
if (IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -526,9 +526,9 @@ public virtual bool UnionWith(IEnumerable other)
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
- public void IntersectWith(IEnumerable other)
+ public void IntersectWith(IEnumerable other) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
// LUCENENET - no modifications should be made outside of original
@@ -536,9 +536,9 @@ public void IntersectWith(IEnumerable other)
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
- public void ExceptWith(IEnumerable other)
+ public void ExceptWith(IEnumerable other) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
// LUCENENET - no modifications should be made outside of original
@@ -546,9 +546,9 @@ public void ExceptWith(IEnumerable other)
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
- public void SymmetricExceptWith(IEnumerable other)
+ public void SymmetricExceptWith(IEnumerable other) // LUCENENET TODO: API - make an explicit implementation that isn't public
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -1143,7 +1143,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
}
if (set.IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -1171,7 +1171,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
}
if (set.IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -1199,7 +1199,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
// }
// if (set.IsReadOnly)
// {
- // throw new InvalidOperationException("CharArraySet is readonly");
+ // throw UnsupportedOperationException.Create("CharArraySet is readonly");
// }
// bool modified = false;
// foreach (var item in other)
@@ -1227,7 +1227,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
// }
// if (set.IsReadOnly)
// {
- // throw new InvalidOperationException("CharArraySet is readonly");
+ // throw UnsupportedOperationException.Create("CharArraySet is readonly");
// }
// bool modified = false;
// foreach (var item in other)
@@ -1255,7 +1255,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
// }
// if (set.IsReadOnly)
// {
- // throw new InvalidOperationException("CharArraySet is readonly");
+ // throw UnsupportedOperationException.Create("CharArraySet is readonly");
// }
// bool modified = false;
// foreach (var item in other)
@@ -1283,7 +1283,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
}
if (set.IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -1311,7 +1311,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
}
if (set.IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -1340,7 +1340,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
}
if (set.IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -1368,7 +1368,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
}
if (set.IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -1397,7 +1397,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
}
if (set.IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -1426,7 +1426,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
}
if (set.IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
@@ -1455,7 +1455,7 @@ public static bool UnionWith(this CharArraySet set, IEnumerable other)
}
if (set.IsReadOnly)
{
- throw new InvalidOperationException("CharArraySet is readonly");
+ throw UnsupportedOperationException.Create("CharArraySet is readonly");
}
bool modified = false;
foreach (var item in other)
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Util/CharacterUtils.cs b/src/Lucene.Net.Analysis.Common/Analysis/Util/CharacterUtils.cs
index 4e9c2fdbd0..54b20399e5 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Util/CharacterUtils.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Util/CharacterUtils.cs
@@ -1,11 +1,10 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N;
using J2N.Text;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using Lucene.Net.Util;
using System;
-using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
@@ -86,7 +85,7 @@ public static CharacterUtils GetJava4Instance(LuceneVersion matchVersion) // LUC
/// the offset to the char values in the chars array to be converted
///
/// the Unicode code point at the given index
- ///
+ ///
/// - if the sequence is null.
///
/// - if the value offset is negative or not less than the length of
@@ -106,7 +105,7 @@ public static CharacterUtils GetJava4Instance(LuceneVersion matchVersion) // LUC
/// the offset to the char values in the chars array to be converted
///
/// the Unicode code point at the given index
- ///
+ ///
/// - if the sequence is null.
///
/// - if the value offset is negative or not less than the length of
@@ -129,7 +128,7 @@ public static CharacterUtils GetJava4Instance(LuceneVersion matchVersion) // LUC
/// codepoint.
///
/// the Unicode code point at the given index
- ///
+ ///
/// - if the array is null.
///
/// - if the value offset is negative or not less than the length of
@@ -163,7 +162,8 @@ public static CharacterBuffer NewCharacterBuffer(int bufferSize)
{
if (bufferSize < 2)
{
- throw new ArgumentException("buffersize must be >= 2");
+ // LUCENENET: Changed from InvalidArgumentException to ArgumentOutOfRangeException
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), "buffersize must be >= 2");
}
return new CharacterBuffer(new char[bufferSize], 0, 0);
}
@@ -244,7 +244,8 @@ public int ToCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int dest
{
if (srcLen < 0)
{
- throw new ArgumentException("srcLen must be >= 0");
+ // LUCENENET: Changed from InvalidArgumentException to ArgumentOutOfRangeException
+ throw new ArgumentOutOfRangeException(nameof(srcLen), "srcLen must be >= 0");
}
int codePointCount = 0;
for (int i = 0; i < srcLen; )
@@ -264,7 +265,8 @@ public int ToChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff)
{
if (srcLen < 0)
{
- throw new ArgumentException("srcLen must be >= 0");
+ // LUCENENET: Changed from InvalidArgumentException to ArgumentOutOfRangeException
+ throw new ArgumentOutOfRangeException(nameof(srcLen), "srcLen must be >= 0");
}
int written = 0;
for (int i = 0; i < srcLen; ++i)
@@ -359,7 +361,8 @@ public override bool Fill(CharacterBuffer buffer, TextReader reader, int numChar
if (Debugging.AssertsEnabled) Debugging.Assert(buffer.Buffer.Length >= 2);
if (numChars < 2 || numChars > buffer.Buffer.Length)
{
- throw new ArgumentException("numChars must be >= 2 and <= the buffer size");
+ // LUCENENET: Changed from InvalidArgumentException to ArgumentOutOfRangeException
+ throw new ArgumentOutOfRangeException(nameof(numChars), "numChars must be >= 2 and <= the buffer size");
}
char[] charBuffer = buffer.Buffer;
buffer.offset = 0;
@@ -398,7 +401,7 @@ public override bool Fill(CharacterBuffer buffer, TextReader reader, int numChar
public override int CodePointCount(string seq)
{
if (seq is null)
- throw new ArgumentNullException(nameof(seq));
+ throw new ArgumentNullException(nameof(seq)); // LUCENENET specific - added null guard clause
return Character.CodePointCount(seq, 0, seq.Length);
}
@@ -406,7 +409,7 @@ public override int CodePointCount(string seq)
public override int CodePointCount(ICharSequence seq)
{
if (seq is null)
- throw new ArgumentNullException(nameof(seq));
+ throw new ArgumentNullException(nameof(seq)); // LUCENENET specific - added null guard clause
return Character.CodePointCount(seq, 0, seq.Length);
}
@@ -414,7 +417,7 @@ public override int CodePointCount(ICharSequence seq)
public override int CodePointCount(char[] seq)
{
if (seq is null)
- throw new ArgumentNullException(nameof(seq));
+ throw new ArgumentNullException(nameof(seq)); // LUCENENET specific - added null guard clause
return Character.CodePointCount(seq, 0, seq.Length);
}
@@ -422,7 +425,7 @@ public override int CodePointCount(char[] seq)
public override int CodePointCount(StringBuilder seq)
{
if (seq is null)
- throw new ArgumentNullException(nameof(seq));
+ throw new ArgumentNullException(nameof(seq)); // LUCENENET specific - added null guard clause
return Character.CodePointCount(seq, 0, seq.Length);
}
@@ -463,10 +466,10 @@ public override int CodePointAt(ICharSequence seq, int offset)
public override int CodePointAt(char[] chars, int offset, int limit)
{
if (chars == null)
- throw new ArgumentNullException(nameof(chars)); // LUCENENET specific - added for .NET compatibility
+ throw new ArgumentNullException(nameof(chars)); // LUCENENET specific - added null guard clause
if (offset >= limit)
{
- throw new ArgumentOutOfRangeException("offset must be less than limit");
+ throw new ArgumentOutOfRangeException(nameof(offset), "offset must be less than limit");
}
// LUCENENET specific - added array bound check
if (offset < 0 || offset >= chars.Length)
@@ -480,7 +483,8 @@ public override bool Fill(CharacterBuffer buffer, TextReader reader, int numChar
if (Debugging.AssertsEnabled) Debugging.Assert(buffer.Buffer.Length >= 1);
if (numChars < 1 || numChars > buffer.Buffer.Length)
{
- throw new ArgumentException("numChars must be >= 1 and <= the buffer size");
+ // LUCENENET: Changed from InvalidArgumentException to ArgumentOutOfRangeException
+ throw new ArgumentOutOfRangeException(nameof(numChars), "numChars must be >= 1 and <= the buffer size");
}
buffer.offset = 0;
int read = ReadFully(reader, buffer.Buffer, 0, numChars);
@@ -492,7 +496,7 @@ public override bool Fill(CharacterBuffer buffer, TextReader reader, int numChar
public override int CodePointCount(string seq)
{
if (seq is null)
- throw new ArgumentNullException(nameof(seq));
+ throw new ArgumentNullException(nameof(seq)); // LUCENENET specific - added null guard clause
return seq.Length;
}
@@ -500,7 +504,7 @@ public override int CodePointCount(string seq)
public override int CodePointCount(ICharSequence seq)
{
if (seq is null)
- throw new ArgumentNullException(nameof(seq));
+ throw new ArgumentNullException(nameof(seq)); // LUCENENET specific - added null guard clause
return seq.Length;
}
@@ -508,7 +512,7 @@ public override int CodePointCount(ICharSequence seq)
public override int CodePointCount(char[] seq)
{
if (seq is null)
- throw new ArgumentNullException(nameof(seq));
+ throw new ArgumentNullException(nameof(seq)); // LUCENENET specific - added null guard clause
return seq.Length;
}
@@ -516,7 +520,7 @@ public override int CodePointCount(char[] seq)
public override int CodePointCount(StringBuilder seq)
{
if (seq is null)
- throw new ArgumentNullException(nameof(seq));
+ throw new ArgumentNullException(nameof(seq)); // LUCENENET specific - added null guard clause
return seq.Length;
}
@@ -526,7 +530,7 @@ public override int OffsetByCodePoints(char[] buf, int start, int count, int ind
int result = index + offset;
if (result < 0 || result > count)
{
- throw new ArgumentOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(index) + " + " + nameof(offset), "index + offset must be >= 0 and <= count");
}
return result;
}
@@ -540,6 +544,9 @@ private class Java4CharacterUtilsBWCompatibility : Java4CharacterUtils
{
public override void ToLower(char[] buffer, int offset, int limit)
{
+ if (buffer is null)
+ throw new ArgumentNullException(nameof(buffer)); // LUCENENET specific - added null guard clause
+
if (Debugging.AssertsEnabled)
{
Debugging.Assert(buffer.Length >= limit);
@@ -556,6 +563,9 @@ public override void ToLower(char[] buffer, int offset, int limit)
public override void ToUpper(char[] buffer, int offset, int limit)
{
+ if (buffer is null)
+ throw new ArgumentNullException(nameof(buffer)); // LUCENENET specific - added null guard clause
+
if (Debugging.AssertsEnabled)
{
Debugging.Assert(buffer.Length >= limit);
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Util/ClasspathResourceLoader.cs b/src/Lucene.Net.Analysis.Common/Analysis/Util/ClasspathResourceLoader.cs
index 2d8c959bd4..5c3d4826c3 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Util/ClasspathResourceLoader.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Util/ClasspathResourceLoader.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N;
using System;
using System.IO;
@@ -73,9 +73,9 @@ public Type FindType(string cname)
return this.clazz.Assembly.GetType(cname, true);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception("Cannot load class: " + cname, e);
+ throw RuntimeException.Create("Cannot load class: " + cname, e);
}
}
@@ -86,9 +86,9 @@ public T NewInstance(string cname)
{
return (T)Activator.CreateInstance(clazz);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception("Cannot create instance: " + cname, e);
+ throw RuntimeException.Create("Cannot create instance: " + cname, e);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Util/FilesystemResourceLoader.cs b/src/Lucene.Net.Analysis.Common/Analysis/Util/FilesystemResourceLoader.cs
index 6d8f2c68dd..7b05a8f12f 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Util/FilesystemResourceLoader.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Util/FilesystemResourceLoader.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using System;
using System.IO;
@@ -72,13 +72,13 @@ public FilesystemResourceLoader(DirectoryInfo baseDirectory, IResourceLoader @de
{
// LUCENENET NOTE: If you call DirectoryInfo.Create() it doesn't set the DirectoryInfo.Exists
// flag to true, so we use the Directory object to check the path explicitly.
- if (baseDirectory != null && !Directory.Exists(baseDirectory.FullName))
+ if (!(baseDirectory is null) && !Directory.Exists(baseDirectory.FullName))
{
- throw new ArgumentException("baseDirectory is not a directory or null");
+ throw new ArgumentException("baseDirectory is not a directory or is null");
}
- if (@delegate == null)
+ if (@delegate is null)
{
- throw new ArgumentException("delegate ResourceLoader may not be null");
+ throw new ArgumentNullException(nameof(@delegate), "delegate IResourceLoader may not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
this.baseDirectory = baseDirectory;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Wikipedia/WikipediaTokenizer.cs b/src/Lucene.Net.Analysis.Common/Analysis/Wikipedia/WikipediaTokenizer.cs
index 42df03c3a2..ca83fb4e86 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Wikipedia/WikipediaTokenizer.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Wikipedia/WikipediaTokenizer.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Support;
using Lucene.Net.Util;
@@ -165,7 +165,7 @@ private void Init(int tokenOutput, ICollection untokenizedTypes)
// TODO: cutover to enum
if (tokenOutput != TOKENS_ONLY && tokenOutput != UNTOKENIZED_ONLY && tokenOutput != BOTH)
{
- throw new ArgumentException("tokenOutput must be TOKENS_ONLY, UNTOKENIZED_ONLY or BOTH");
+ throw new ArgumentOutOfRangeException(nameof(tokenOutput), "tokenOutput must be TOKENS_ONLY, UNTOKENIZED_ONLY or BOTH"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.tokenOutput = tokenOutput;
this.untokenizedTypes = untokenizedTypes;
diff --git a/src/Lucene.Net.Analysis.Common/Analysis/Wikipedia/WikipediaTokenizerImpl.cs b/src/Lucene.Net.Analysis.Common/Analysis/Wikipedia/WikipediaTokenizerImpl.cs
index 4506057062..a1f68463a9 100644
--- a/src/Lucene.Net.Analysis.Common/Analysis/Wikipedia/WikipediaTokenizerImpl.cs
+++ b/src/Lucene.Net.Analysis.Common/Analysis/Wikipedia/WikipediaTokenizerImpl.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
@@ -706,16 +706,17 @@ public char YyCharAt(int pos)
private void ZzScanError(int errorCode)
{
string message;
- try
+ // LUCENENET specific: Defensive check so we don't have to catch IndexOutOfRangeException
+ if (errorCode >= 0 && errorCode < ZZ_ERROR_MSG.Length)
{
message = ZZ_ERROR_MSG[errorCode];
}
- catch (IndexOutOfRangeException /*e*/)
+ else
{
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
- throw new Exception(message);
+ throw Error.Create(message);
}
diff --git a/src/Lucene.Net.Analysis.ICU/Analysis/Icu/ICUNormalizer2CharFilter.cs b/src/Lucene.Net.Analysis.ICU/Analysis/Icu/ICUNormalizer2CharFilter.cs
index 93018bb574..5dc99b0bc4 100644
--- a/src/Lucene.Net.Analysis.ICU/Analysis/Icu/ICUNormalizer2CharFilter.cs
+++ b/src/Lucene.Net.Analysis.ICU/Analysis/Icu/ICUNormalizer2CharFilter.cs
@@ -63,22 +63,22 @@ public ICUNormalizer2CharFilter(TextReader input)
public ICUNormalizer2CharFilter(TextReader input, Normalizer2 normalizer)
: this(input, normalizer, 128)
{
- this.normalizer = normalizer ?? throw new ArgumentNullException(nameof(normalizer));
+ this.normalizer = normalizer ?? throw new ArgumentNullException(nameof(normalizer)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
// for testing ONLY
internal ICUNormalizer2CharFilter(TextReader input, Normalizer2 normalizer, int bufferSize)
: base(input)
{
- this.normalizer = normalizer ?? throw new ArgumentNullException(nameof(normalizer));
+ this.normalizer = normalizer ?? throw new ArgumentNullException(nameof(normalizer)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
this.tmpBuffer = CharacterUtils.NewCharacterBuffer(bufferSize);
}
public override int Read(char[] cbuf, int off, int len)
{
- if (off < 0) throw new ArgumentException("off < 0");
- if (off >= cbuf.Length) throw new ArgumentException("off >= cbuf.length");
- if (len <= 0) throw new ArgumentException("len <= 0");
+ if (off < 0) throw new ArgumentOutOfRangeException(nameof(off), "off < 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
+ if (off >= cbuf.Length) throw new ArgumentOutOfRangeException(nameof(off), "off >= cbuf.length"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
+ if (len <= 0) throw new ArgumentOutOfRangeException(nameof(len), "len <= 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
while (!inputFinished || inputBuffer.Length > 0 || resultBuffer.Length > 0)
{
diff --git a/src/Lucene.Net.Analysis.ICU/Analysis/Icu/Segmentation/DefaultICUTokenizerConfig.cs b/src/Lucene.Net.Analysis.ICU/Analysis/Icu/Segmentation/DefaultICUTokenizerConfig.cs
index ef3444d6cf..9981c5fff8 100644
--- a/src/Lucene.Net.Analysis.ICU/Analysis/Icu/Segmentation/DefaultICUTokenizerConfig.cs
+++ b/src/Lucene.Net.Analysis.ICU/Analysis/Icu/Segmentation/DefaultICUTokenizerConfig.cs
@@ -138,9 +138,9 @@ private static RuleBasedBreakIterator ReadBreakIterator(string filename)
RuleBasedBreakIterator.GetInstanceFromCompiledRules(@is);
return bi;
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
}
diff --git a/src/Lucene.Net.Analysis.ICU/Collation/ICUCollationKeyFilterFactory.cs b/src/Lucene.Net.Analysis.ICU/Collation/ICUCollationKeyFilterFactory.cs
index dd30193408..55d316d1cc 100644
--- a/src/Lucene.Net.Analysis.ICU/Collation/ICUCollationKeyFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.ICU/Collation/ICUCollationKeyFilterFactory.cs
@@ -98,7 +98,7 @@ public ICUCollationKeyFilterFactory(IDictionary args)
if (custom != null && localeID != null)
throw new ArgumentException("Cannot specify both locale and custom. "
- + "To tailor rules for a built-in language, see the javadocs for RuleBasedCollator. "
+ + "To tailor rules for a built-in language, see the docs for RuleBasedCollator. "
+ "Then save the entire customized ruleset to a file, and use with the custom parameter");
if (args.Count > 0)
@@ -224,10 +224,10 @@ private Collator CreateFromRules(string fileName, IResourceLoader loader)
string rules = ToUTF8String(input);
return new RuleBasedCollator(rules);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
// io error or invalid rules
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
finally
{
diff --git a/src/Lucene.Net.Analysis.Kuromoji/Dict/BinaryDictionary.cs b/src/Lucene.Net.Analysis.Kuromoji/Dict/BinaryDictionary.cs
index 9ca9d5d381..8ce02fd1de 100644
--- a/src/Lucene.Net.Analysis.Kuromoji/Dict/BinaryDictionary.cs
+++ b/src/Lucene.Net.Analysis.Kuromoji/Dict/BinaryDictionary.cs
@@ -166,7 +166,7 @@ protected BinaryDictionary()
int read = dictIS.Read(tmpBuffer.Array, 0, size);
if (read != size)
{
- throw new EndOfStreamException("Cannot read whole dictionary");
+ throw EOFException.Create("Cannot read whole dictionary");
}
}
buffer = tmpBuffer.AsReadOnlyBuffer();
diff --git a/src/Lucene.Net.Analysis.Kuromoji/Dict/CharacterDefinition.cs b/src/Lucene.Net.Analysis.Kuromoji/Dict/CharacterDefinition.cs
index 2d6b285785..4a63d62af5 100644
--- a/src/Lucene.Net.Analysis.Kuromoji/Dict/CharacterDefinition.cs
+++ b/src/Lucene.Net.Analysis.Kuromoji/Dict/CharacterDefinition.cs
@@ -109,9 +109,9 @@ private static CharacterDefinition LoadInstance() // LUCENENET: Avoid static con
{
return new CharacterDefinition();
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new Exception("Cannot load CharacterDefinition.", ioe);
+ throw RuntimeException.Create("Cannot load CharacterDefinition.", ioe);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Kuromoji/Dict/ConnectionCosts.cs b/src/Lucene.Net.Analysis.Kuromoji/Dict/ConnectionCosts.cs
index 3845a77253..fa3f29a9c5 100644
--- a/src/Lucene.Net.Analysis.Kuromoji/Dict/ConnectionCosts.cs
+++ b/src/Lucene.Net.Analysis.Kuromoji/Dict/ConnectionCosts.cs
@@ -78,9 +78,9 @@ private static ConnectionCosts LoadInstance() // LUCENENET: Avoid static constru
{
return new ConnectionCosts();
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new Exception("Cannot load ConnectionCosts.", ioe);
+ throw RuntimeException.Create("Cannot load ConnectionCosts.", ioe);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Kuromoji/Dict/TokenInfoDictionary.cs b/src/Lucene.Net.Analysis.Kuromoji/Dict/TokenInfoDictionary.cs
index d278e00f93..7055153f9e 100644
--- a/src/Lucene.Net.Analysis.Kuromoji/Dict/TokenInfoDictionary.cs
+++ b/src/Lucene.Net.Analysis.Kuromoji/Dict/TokenInfoDictionary.cs
@@ -56,9 +56,9 @@ private static TokenInfoDictionary LoadInstance() // LUCENENET: Avoid static con
{
return new TokenInfoDictionary();
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new Exception("Cannot load TokenInfoDictionary.", ioe);
+ throw RuntimeException.Create("Cannot load TokenInfoDictionary.", ioe);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Kuromoji/Dict/UnknownDictionary.cs b/src/Lucene.Net.Analysis.Kuromoji/Dict/UnknownDictionary.cs
index 1353ce3e82..24455993b6 100644
--- a/src/Lucene.Net.Analysis.Kuromoji/Dict/UnknownDictionary.cs
+++ b/src/Lucene.Net.Analysis.Kuromoji/Dict/UnknownDictionary.cs
@@ -84,9 +84,9 @@ private static UnknownDictionary LoadInstance() // LUCENENET: Avoid static const
{
return new UnknownDictionary();
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new Exception("Cannot load UnknownDictionary.", ioe);
+ throw RuntimeException.Create("Cannot load UnknownDictionary.", ioe);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Kuromoji/Dict/UserDictionary.cs b/src/Lucene.Net.Analysis.Kuromoji/Dict/UserDictionary.cs
index e42ce66e1b..974d506901 100644
--- a/src/Lucene.Net.Analysis.Kuromoji/Dict/UserDictionary.cs
+++ b/src/Lucene.Net.Analysis.Kuromoji/Dict/UserDictionary.cs
@@ -96,7 +96,7 @@ public UserDictionary(TextReader reader)
if (segmentation.Length != readings.Length)
{
- throw new Exception("Illegal user dictionary entry " + values[0] +
+ throw RuntimeException.Create("Illegal user dictionary entry " + values[0] +
" - the number of segmentations (" + segmentation.Length + ")" +
" does not the match number of readings (" + readings.Length + ")");
}
diff --git a/src/Lucene.Net.Analysis.Kuromoji/JapaneseAnalyzer.cs b/src/Lucene.Net.Analysis.Kuromoji/JapaneseAnalyzer.cs
index 49a1bc6c2f..e978abc431 100644
--- a/src/Lucene.Net.Analysis.Kuromoji/JapaneseAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Kuromoji/JapaneseAnalyzer.cs
@@ -75,10 +75,10 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadStopwordSet(true, typeof(JapaneseAnalyzer), "stopwords.txt", "#"); // ignore case
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
@@ -94,10 +94,10 @@ private static ISet LoadDefaultStopTagSet() // LUCENENET: Avoid static c
}
return DEFAULT_STOP_TAGS;
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the distribution (JAR)
- throw new Exception("Unable to load default stoptag set", ex);
+ throw RuntimeException.Create("Unable to load default stoptag set", ex);
}
}
}
diff --git a/src/Lucene.Net.Analysis.Kuromoji/JapaneseKatakanaStemFilterFactory.cs b/src/Lucene.Net.Analysis.Kuromoji/JapaneseKatakanaStemFilterFactory.cs
index ec322ee398..0b3b66a158 100644
--- a/src/Lucene.Net.Analysis.Kuromoji/JapaneseKatakanaStemFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.Kuromoji/JapaneseKatakanaStemFilterFactory.cs
@@ -45,7 +45,7 @@ public JapaneseKatakanaStemFilterFactory(IDictionary args)
minimumLength = GetInt32(args, MINIMUM_LENGTH_PARAM, JapaneseKatakanaStemFilter.DEFAULT_MINIMUM_LENGTH);
if (minimumLength < 2)
{
- throw new ArgumentException("Illegal " + MINIMUM_LENGTH_PARAM + " " + minimumLength + " (must be 2 or greater)");
+ throw new ArgumentOutOfRangeException(nameof(minimumLength), "Illegal " + MINIMUM_LENGTH_PARAM + " " + minimumLength + " (must be 2 or greater)"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (args.Count > 0)
{
diff --git a/src/Lucene.Net.Analysis.Kuromoji/Util/ToStringUtil.cs b/src/Lucene.Net.Analysis.Kuromoji/Util/ToStringUtil.cs
index f88421c5bf..16cff4da46 100644
--- a/src/Lucene.Net.Analysis.Kuromoji/Util/ToStringUtil.cs
+++ b/src/Lucene.Net.Analysis.Kuromoji/Util/ToStringUtil.cs
@@ -258,9 +258,9 @@ public static string GetRomanization(string s)
{
GetRomanization(result, s);
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.ToString(), bogus);
+ throw RuntimeException.Create(bogus);
}
return result.ToString();
}
diff --git a/src/Lucene.Net.Analysis.Morfologik/Uk/UkrainianMorfologikAnalyzer.cs b/src/Lucene.Net.Analysis.Morfologik/Uk/UkrainianMorfologikAnalyzer.cs
index 1e97edb02c..d115cbe3c4 100644
--- a/src/Lucene.Net.Analysis.Morfologik/Uk/UkrainianMorfologikAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Morfologik/Uk/UkrainianMorfologikAnalyzer.cs
@@ -66,11 +66,11 @@ private static CharArraySet LoadDefaultSet()
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
}
@@ -166,9 +166,9 @@ private static Dictionary GetDictionary()
using var metadataStream = type.FindAndGetManifestResourceStream(DictionaryMetadata.GetExpectedMetadataFileName(dictFile));
return Dictionary.Read(dictStream, metadataStream);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
}
diff --git a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPChunkerFilterFactory.cs b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPChunkerFilterFactory.cs
index 53d37503cd..2206ccfb6e 100644
--- a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPChunkerFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPChunkerFilterFactory.cs
@@ -65,7 +65,7 @@ public override TokenStream Create(TokenStream input)
}
return new OpenNLPChunkerFilter(input, chunkerOp);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
throw new ArgumentException(e.ToString(), e);
}
@@ -81,7 +81,7 @@ public virtual void Inform(IResourceLoader loader)
OpenNLPOpsFactory.GetChunkerModel(chunkerModelFile, loader);
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
throw new ArgumentException(e.ToString(), e);
}
diff --git a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPLemmatizerFilterFactory.cs b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPLemmatizerFilterFactory.cs
index 5d4b6970b2..d4bc59d3e8 100644
--- a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPLemmatizerFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPLemmatizerFilterFactory.cs
@@ -73,9 +73,9 @@ public override TokenStream Create(TokenStream input)
NLPLemmatizerOp lemmatizerOp = OpenNLPOpsFactory.GetLemmatizer(dictionaryFile, lemmatizerModelFile);
return new OpenNLPLemmatizerFilter(input, lemmatizerOp);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
diff --git a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPPOSFilterFactory.cs b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPPOSFilterFactory.cs
index 5f112c2d33..8008c0d3c9 100644
--- a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPPOSFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPPOSFilterFactory.cs
@@ -58,7 +58,7 @@ public override TokenStream Create(TokenStream input)
{
return new OpenNLPPOSFilter(input, OpenNLPOpsFactory.GetPOSTagger(posTaggerModelFile));
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
throw new ArgumentException(e.ToString(), e);
}
@@ -70,7 +70,7 @@ public virtual void Inform(IResourceLoader loader)
{ // load and register the read-only model in cache with file/resource name
OpenNLPOpsFactory.GetPOSTaggerModel(posTaggerModelFile, loader);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
throw new ArgumentException(e.ToString(), e);
}
diff --git a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPSentenceBreakIterator.cs b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPSentenceBreakIterator.cs
index 6e12869a25..3be1834412 100644
--- a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPSentenceBreakIterator.cs
+++ b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPSentenceBreakIterator.cs
@@ -87,7 +87,7 @@ public override int Following(int pos)
{
if (pos < text.BeginIndex || pos > text.EndIndex)
{
- throw new ArgumentException("offset out of bounds");
+ throw new ArgumentOutOfRangeException(nameof(pos), "offset out of bounds: must be >= text.BeginIndex and <= text.EndIndex"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
else if (0 == sentenceStarts.Length)
{
@@ -168,7 +168,7 @@ public override int Preceding(int pos)
{
if (pos < text.BeginIndex || pos > text.EndIndex)
{
- throw new ArgumentException("offset out of bounds");
+ throw new ArgumentOutOfRangeException(nameof(pos), "offset out of bounds: must be >= text.BeginIndex and <= text.EndIndex"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
else if (0 == sentenceStarts.Length)
{
diff --git a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPTokenizer.cs b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPTokenizer.cs
index 1eed0803f5..eb9f6ec081 100644
--- a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPTokenizer.cs
+++ b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPTokenizer.cs
@@ -55,10 +55,11 @@ public sealed class OpenNLPTokenizer : SegmentingTokenizerBase
public OpenNLPTokenizer(AttributeFactory factory, TextReader reader, NLPSentenceDetectorOp sentenceOp, NLPTokenizerOp tokenizerOp) // LUCENENET: Added reader param for compatibility with 4.8 - remove when upgrading
: base(factory, reader, new OpenNLPSentenceBreakIterator(sentenceOp))
{
- if (sentenceOp == null || tokenizerOp == null)
- {
- throw new ArgumentException("OpenNLPTokenizer: both a Sentence Detector and a Tokenizer are required");
- }
+ // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) and refactored to throw on each one separately
+ if (sentenceOp is null)
+ throw new ArgumentNullException(nameof(sentenceOp), "OpenNLPTokenizer: both a Sentence Detector and a Tokenizer are required");
+ if (tokenizerOp is null)
+ throw new ArgumentNullException(nameof(tokenizerOp), "OpenNLPTokenizer: both a Sentence Detector and a Tokenizer are required");
//this.sentenceOp = sentenceOp; // LUCENENET: Never read
this.tokenizerOp = tokenizerOp;
this.termAtt = AddAttribute();
diff --git a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPTokenizerFactory.cs b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPTokenizerFactory.cs
index 22ddd9b06d..5940b7de02 100644
--- a/src/Lucene.Net.Analysis.OpenNLP/OpenNLPTokenizerFactory.cs
+++ b/src/Lucene.Net.Analysis.OpenNLP/OpenNLPTokenizerFactory.cs
@@ -63,9 +63,9 @@ public override Tokenizer Create(AttributeFactory factory, TextReader reader)
NLPTokenizerOp tokenizerOp = OpenNLPOpsFactory.GetTokenizer(tokenizerModelFile);
return new OpenNLPTokenizer(factory, reader, sentenceOp, tokenizerOp);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
diff --git a/src/Lucene.Net.Analysis.Phonetic/Language/Bm/PhoneticEngine.cs b/src/Lucene.Net.Analysis.Phonetic/Language/Bm/PhoneticEngine.cs
index fedc8ded7e..4b1f945f51 100644
--- a/src/Lucene.Net.Analysis.Phonetic/Language/Bm/PhoneticEngine.cs
+++ b/src/Lucene.Net.Analysis.Phonetic/Language/Bm/PhoneticEngine.cs
@@ -214,7 +214,7 @@ private sealed class RulesApplication
public RulesApplication(IDictionary> finalRules, string input,
PhonemeBuilder phonemeBuilder, int i, int maxPhonemes)
{
- this.finalRules = finalRules ?? throw new ArgumentNullException(nameof(finalRules), "The finalRules argument must not be null");
+ this.finalRules = finalRules ?? throw new ArgumentNullException(nameof(finalRules), "The finalRules argument must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
this.phonemeBuilder = phonemeBuilder;
this.input = input;
this.i = i;
@@ -358,7 +358,7 @@ private PhonemeBuilder ApplyFinalRules(PhonemeBuilder phonemeBuilder,
{
if (finalRules == null)
{
- throw new ArgumentNullException("finalRules can not be null");
+ throw new ArgumentNullException("finalRules can not be null");// LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (finalRules.Count == 0)
{
diff --git a/src/Lucene.Net.Analysis.Phonetic/Language/Bm/Rule.cs b/src/Lucene.Net.Analysis.Phonetic/Language/Bm/Rule.cs
index 05c6633d51..03116bdc6c 100644
--- a/src/Lucene.Net.Analysis.Phonetic/Language/Bm/Rule.cs
+++ b/src/Lucene.Net.Analysis.Phonetic/Language/Bm/Rule.cs
@@ -140,7 +140,7 @@ private static IDictionary> ParseRules(TextReader reader, st
}
rules.Add(r);
}
- catch (ArgumentException e)
+ catch (Exception e) when (e.IsIllegalArgumentException())
{
throw new InvalidOperationException("Problem parsing line '" + currentLine + "' in " +
location, e);
@@ -835,7 +835,7 @@ public virtual bool PatternAndContextMatches(ICharSequence input, int i)
{
if (i < 0)
{
- throw new ArgumentOutOfRangeException("Can not match pattern at negative indexes");
+ throw new ArgumentOutOfRangeException(nameof(i), "Can not match pattern at negative indexes");// LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
int patternLength = this.pattern.Length;
@@ -873,7 +873,7 @@ public virtual bool PatternAndContextMatches(string input, int i)
{
if (i < 0)
{
- throw new ArgumentOutOfRangeException("Can not match pattern at negative indexes");
+ throw new ArgumentOutOfRangeException(nameof(i), "Can not match pattern at negative indexes");// LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
int patternLength = this.pattern.Length;
@@ -911,7 +911,7 @@ public virtual bool PatternAndContextMatches(StringBuilder input, int i)
{
if (i < 0)
{
- throw new ArgumentOutOfRangeException("Can not match pattern at negative indexes");
+ throw new ArgumentOutOfRangeException(nameof(i), "Can not match pattern at negative indexes");// LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
int patternLength = this.pattern.Length;
diff --git a/src/Lucene.Net.Analysis.Phonetic/Language/DaitchMokotoffSoundex.cs b/src/Lucene.Net.Analysis.Phonetic/Language/DaitchMokotoffSoundex.cs
index 88c92a4bde..f8f8ee8a1a 100644
--- a/src/Lucene.Net.Analysis.Phonetic/Language/DaitchMokotoffSoundex.cs
+++ b/src/Lucene.Net.Analysis.Phonetic/Language/DaitchMokotoffSoundex.cs
@@ -363,7 +363,7 @@ private static void ParseRules(TextReader scanner, string location,
}
rules.Add(r);
}
- catch (ArgumentException e)
+ catch (Exception e) when (e.IsIllegalArgumentException())
{
throw new InvalidOperationException(
"Problem parsing line '" + currentLine + "' in " + location, e);
diff --git a/src/Lucene.Net.Analysis.Phonetic/PhoneticFilter.cs b/src/Lucene.Net.Analysis.Phonetic/PhoneticFilter.cs
index a6664f302d..b664168c32 100644
--- a/src/Lucene.Net.Analysis.Phonetic/PhoneticFilter.cs
+++ b/src/Lucene.Net.Analysis.Phonetic/PhoneticFilter.cs
@@ -76,7 +76,7 @@ public override bool IncrementToken()
phonetic = v;
}
}
- catch (Exception) { /* ignored */ } // just use the direct text
+ catch (Exception ignored) when (ignored.IsException()) { } // just use the direct text
if (phonetic == null) return true;
diff --git a/src/Lucene.Net.Analysis.Phonetic/PhoneticFilterFactory.cs b/src/Lucene.Net.Analysis.Phonetic/PhoneticFilterFactory.cs
index 529e3159a3..708cf5161c 100644
--- a/src/Lucene.Net.Analysis.Phonetic/PhoneticFilterFactory.cs
+++ b/src/Lucene.Net.Analysis.Phonetic/PhoneticFilterFactory.cs
@@ -129,7 +129,7 @@ public virtual void Inform(IResourceLoader loader)
{
setMaxCodeLenMethod = clazz.GetMethod("set_MaxCodeLen");
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
throw new ArgumentException("Encoder " + name + " / " + clazz + " does not support " + MAX_CODE_LENGTH, e);
}
@@ -149,7 +149,7 @@ private Type ResolveEncoder(string name, IResourceLoader loader)
{
return loader.NewInstance(lookupName).GetType();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsRuntimeException())
{
throw new ArgumentException("Error loading encoder '" + name + "': must be full class name or one of " + Collections.ToString(registry.Keys), e);
}
@@ -170,7 +170,7 @@ protected internal virtual IStringEncoder GetEncoder()
}
return encoder;
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
Exception t = (e is TargetInvocationException) ? e.InnerException : e;
throw new ArgumentException("Error initializing encoder: " + name + " / " + clazz, t);
diff --git a/src/Lucene.Net.Analysis.SmartCn/Hhmm/AbstractDictionary.cs b/src/Lucene.Net.Analysis.SmartCn/Hhmm/AbstractDictionary.cs
index 67e9a843d8..5e2139018e 100644
--- a/src/Lucene.Net.Analysis.SmartCn/Hhmm/AbstractDictionary.cs
+++ b/src/Lucene.Net.Analysis.SmartCn/Hhmm/AbstractDictionary.cs
@@ -101,7 +101,7 @@ public virtual string GetCCByGB2312Id(int ccid)
string cchar = Encoding.GetEncoding("GB2312").GetString(buffer);
return cchar;
}
- catch (ArgumentException) // Encoding is not supported by the platform
+ catch (Exception e) when (e.IsUnsupportedEncodingException()) // Encoding is not supported by the platform
{
return "";
}
@@ -129,9 +129,9 @@ public virtual short GetGB2312Id(char ch)
// Therefore, each code page only has 16*6-2=94 characters.
return (short)(b0 * 94 + b1);
}
- catch (ArgumentException e) // Encoding is not supported by the platform
+ catch (Exception e) when (e.IsUnsupportedEncodingException()) // Encoding is not supported by the platform
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
diff --git a/src/Lucene.Net.Analysis.SmartCn/Hhmm/BigramDictionary.cs b/src/Lucene.Net.Analysis.SmartCn/Hhmm/BigramDictionary.cs
index ab7bb5d3eb..2925dd6c87 100644
--- a/src/Lucene.Net.Analysis.SmartCn/Hhmm/BigramDictionary.cs
+++ b/src/Lucene.Net.Analysis.SmartCn/Hhmm/BigramDictionary.cs
@@ -72,7 +72,7 @@ public static BigramDictionary GetInstance()
string dictRoot = AnalyzerProfile.ANALYSIS_DATA_DIR;
if (string.IsNullOrEmpty(dictRoot))
{
- singleInstance.Load();
+ singleInstance.Load(); // LUCENENET: No IOException can happen here
}
else
{
@@ -91,9 +91,9 @@ private bool LoadFromObj(FileInfo serialObj)
LoadFromInputStream(input);
return true;
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
@@ -200,7 +200,7 @@ private void SaveToObj(FileInfo serialObj)
// log.info("serialize bigram dict.");
}
#pragma warning disable 168, IDE0059
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
#pragma warning restore 168, IDE0059
{
// log.warn(e.getMessage());
@@ -237,9 +237,9 @@ private void Load(string dictRoot)
}
LoadFromFile(bigramDictPath);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
SaveToObj(serialObj);
}
diff --git a/src/Lucene.Net.Analysis.SmartCn/Hhmm/WordDictionary.cs b/src/Lucene.Net.Analysis.SmartCn/Hhmm/WordDictionary.cs
index 2aadb8d3c6..906e6b3a4c 100644
--- a/src/Lucene.Net.Analysis.SmartCn/Hhmm/WordDictionary.cs
+++ b/src/Lucene.Net.Analysis.SmartCn/Hhmm/WordDictionary.cs
@@ -90,7 +90,7 @@ public static WordDictionary GetInstance()
string dictRoot = AnalyzerProfile.ANALYSIS_DATA_DIR;
if (string.IsNullOrEmpty(dictRoot))
{
- singleInstance.Load();
+ singleInstance.Load(); // LUCENENET: No IOExcpetion can happen here
}
else
{
@@ -134,9 +134,9 @@ public virtual void Load(string dctFileRoot)
SortEachItems();
// log.info("load dictionary: " + dctFilePath + " total:" + total);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e); // LUCENENET: Passing class so we can wrap it
}
SaveToObj(serialObj);
@@ -164,7 +164,7 @@ private bool LoadFromObj(FileInfo serialObj)
}
catch (Exception e)
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
diff --git a/src/Lucene.Net.Analysis.SmartCn/SmartChineseAnalyzer.cs b/src/Lucene.Net.Analysis.SmartCn/SmartChineseAnalyzer.cs
index 8e2e62c22b..f6c2a84d48 100644
--- a/src/Lucene.Net.Analysis.SmartCn/SmartChineseAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.SmartCn/SmartChineseAnalyzer.cs
@@ -77,11 +77,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
{
return LoadDefaultStopWordSet();
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (JAR)
- throw new Exception("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
diff --git a/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/Compile.cs b/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/Compile.cs
index 78a71cf5f4..9f5da0d904 100644
--- a/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/Compile.cs
+++ b/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/Compile.cs
@@ -149,11 +149,10 @@ public static void Main(string[] args)
string line;
while ((line = input.ReadLine()) != null)
{
- try
+ line = line.ToLowerInvariant();
+ using StringTokenizer st = new StringTokenizer(line);
+ if (st.MoveNext())
{
- line = line.ToLowerInvariant();
- StringTokenizer st = new StringTokenizer(line);
- st.MoveNext();
string stem = st.Current;
if (storeorig)
{
@@ -170,7 +169,7 @@ public static void Main(string[] args)
}
}
}
- catch (InvalidOperationException)
+ else // LUCENENET: st.MoveNext() will return false rather than throwing a NoSuchElementException
{
// no base token (stem) on a line
}
diff --git a/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/Diff.cs b/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/Diff.cs
index 713062977d..3b44b2661f 100644
--- a/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/Diff.cs
+++ b/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/Diff.cs
@@ -1,4 +1,5 @@
-using Lucene.Net.Support;
+using Lucene;
+using Lucene.Net.Support;
using System;
using System.Text;
@@ -157,11 +158,11 @@ public static void Apply(StringBuilder dest, string diff)
pos--;
}
}
- catch (IndexOutOfRangeException /*x*/)
+ catch (Exception x) when (x.IsStringIndexOutOfBoundsException())
{
// x.printStackTrace();
}
- catch (ArgumentOutOfRangeException /*x*/)
+ catch (Exception x) when (x.IsArrayIndexOutOfBoundsException())
{
// x.printStackTrace();
}
diff --git a/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/DiffIt.cs b/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/DiffIt.cs
index e7b445427d..eff973d560 100644
--- a/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/DiffIt.cs
+++ b/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/DiffIt.cs
@@ -122,11 +122,10 @@ public static void Main(string[] args)
string line;
while ((line = input.ReadLine()) != null)
{
- try
+ line = line.ToLowerInvariant();
+ using StringTokenizer st = new StringTokenizer(line);
+ if (st.MoveNext())
{
- line = line.ToLowerInvariant();
- StringTokenizer st = new StringTokenizer(line);
- st.MoveNext();
string stem = st.Current;
Console.WriteLine(stem + " -a");
while (st.MoveNext())
@@ -138,7 +137,7 @@ public static void Main(string[] args)
}
}
}
- catch (InvalidOperationException)
+ else // LUCENENET: st.MoveNext() will return false rather than throwing a NoSuchElementException
{
// no base token (stem) on a line
}
diff --git a/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/MultiTrie2.cs b/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/MultiTrie2.cs
index df31f61c6d..38c95c142a 100644
--- a/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/MultiTrie2.cs
+++ b/src/Lucene.Net.Analysis.Stempel/Egothor.Stemmer/MultiTrie2.cs
@@ -1,4 +1,5 @@
using J2N.IO;
+using Lucene;
using System;
using System.Collections.Generic;
using System.IO;
@@ -142,7 +143,7 @@ public override string GetFully(string key)
}
}
}
- catch (ArgumentOutOfRangeException /*x*/) { }
+ catch (Exception x) when (x.IsIndexOutOfBoundsException()) { }
return result.ToString();
}
@@ -200,7 +201,7 @@ public override string GetLastOnPath(string key)
}
}
}
- catch (ArgumentOutOfRangeException /*x*/) { }
+ catch (Exception x) when (x.IsIndexOutOfBoundsException()) { }
return result.ToString();
}
diff --git a/src/Lucene.Net.Analysis.Stempel/Pl/PolishAnalyzer.cs b/src/Lucene.Net.Analysis.Stempel/Pl/PolishAnalyzer.cs
index 23a025b660..cab714698f 100644
--- a/src/Lucene.Net.Analysis.Stempel/Pl/PolishAnalyzer.cs
+++ b/src/Lucene.Net.Analysis.Stempel/Pl/PolishAnalyzer.cs
@@ -77,11 +77,11 @@ private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static cons
LuceneVersion.LUCENE_CURRENT);
#pragma warning restore 612, 618
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (embedded resource)
- throw new InvalidOperationException("Unable to load default stopword set", ex);
+ throw RuntimeException.Create("Unable to load default stopword set", ex);
}
}
@@ -91,11 +91,11 @@ private static Trie LoadDefaultTable() // LUCENENET: Avoid static constructors (
{
return StempelStemmer.Load(typeof(PolishAnalyzer).FindAndGetManifestResourceStream(DEFAULT_STEMMER_FILE));
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
// default set should always be present as it is part of the
// distribution (embedded resource)
- throw new InvalidOperationException("Unable to load default stemming tables", ex);
+ throw RuntimeException.Create("Unable to load default stemming tables", ex);
}
}
}
diff --git a/src/Lucene.Net.Benchmark/ByTask/Benchmark.cs b/src/Lucene.Net.Benchmark/ByTask/Benchmark.cs
index 3fb7a8f276..dc3f504656 100644
--- a/src/Lucene.Net.Benchmark/ByTask/Benchmark.cs
+++ b/src/Lucene.Net.Benchmark/ByTask/Benchmark.cs
@@ -55,9 +55,10 @@ public Benchmark(TextReader algReader)
{
runData = new PerfRunData(new Config(algReader));
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
//e.printStackTrace();
+ Console.Error.WriteLine(e.ToString());
throw new Exception("Error: cannot init PerfRunData!", e);
}
@@ -66,7 +67,7 @@ public Benchmark(TextReader algReader)
{
algorithm = new Algorithm(runData);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
throw new Exception("Error: cannot understand algorithm!", e);
}
@@ -81,7 +82,7 @@ public virtual void Execute()
{
if (executed)
{
- throw new InvalidOperationException("Benchmark was already executed");
+ throw IllegalStateException.Create("Benchmark was already executed");
}
executed = true;
runData.SetStartTimeMillis();
@@ -128,9 +129,9 @@ public static void Exec(string[] args)
{
benchmark = new Benchmark(IOUtils.GetDecodingReader(algFile, Encoding.UTF8));
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- Console.WriteLine(e.ToString());
+ Console.Error.WriteLine(e.ToString());
Environment.Exit(1);
}
@@ -142,10 +143,10 @@ public static void Exec(string[] args)
{
benchmark.Execute();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- Console.WriteLine("Error: cannot execute the algorithm! " + e.Message);
- Console.WriteLine(e.StackTrace);
+ Console.Error.WriteLine("Error: cannot execute the algorithm! " + e.Message);
+ Console.Error.WriteLine(e.ToString());
}
Console.WriteLine("####################");
diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/DirContentSource.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/DirContentSource.cs
index 3868ba3d24..10e0248d11 100644
--- a/src/Lucene.Net.Benchmark/ByTask/Feeds/DirContentSource.cs
+++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/DirContentSource.cs
@@ -254,7 +254,7 @@ public override void SetConfig(Config config)
if (inputFiles == null)
{
- throw new Exception("No txt files in dataDir: " + dataDir.FullName);
+ throw RuntimeException.Create("No txt files in dataDir: " + dataDir.FullName);
}
}
}
diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/DocMaker.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/DocMaker.cs
index 1ac16f3bab..6b2e7af628 100644
--- a/src/Lucene.Net.Benchmark/ByTask/Feeds/DocMaker.cs
+++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/DocMaker.cs
@@ -1,5 +1,6 @@
using J2N.Threading.Atomic;
using Lucene.Net.Benchmarks.ByTask.Utils;
+using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Util;
using System;
@@ -160,7 +161,7 @@ internal Field GetNumericField(string name, NumericType type)
f = new DoubleField(name, 0.0, Field.Store.NO);
break;
default:
- throw new InvalidOperationException("Cannot get here");
+ throw AssertionError.Create("Cannot get here");
}
if (reuseFields)
{
diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/EnwikiContentSource.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/EnwikiContentSource.cs
index 07bb721a06..ce71b77ff0 100644
--- a/src/Lucene.Net.Benchmark/ByTask/Feeds/EnwikiContentSource.cs
+++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/EnwikiContentSource.cs
@@ -77,14 +77,8 @@ internal string[] Next()
{
while (tuple == null && nmde == null && !threadDone && !stopped)
{
- //try
- //{
- Monitor.Wait(this);
- //}
- //catch (ThreadInterruptedException ie)
- //{
- // throw new ThreadInterruptedException(ie.ToString(), ie);
- //}
+ Monitor.Wait(this);
+ // LUCENENET NOTE: No need to catch and rethrow same excepton type ThreadInterruptedException. Note that it could be thrown above on lock (this).
}
if (tuple != null)
{
@@ -148,14 +142,8 @@ public override void EndElement(string @namespace, string simple, string qualifi
{
while (tuple != null && !stopped)
{
- //try
- //{
- Monitor.Wait(this); //wait();
- //}
- //catch (ThreadInterruptedException ie)
- //{
- // throw new ThreadInterruptedException(ie.ToString(), ie);
- //}
+ Monitor.Wait(this);
+ // LUCENENET NOTE: No need to catch and rethrow same excepton type ThreadInterruptedException. Note that it could be thrown above on lock (this).
}
tuple = tmpTuple;
Monitor.Pulse(this); //notify();
@@ -209,7 +197,7 @@ public void Run()
// To work around a bug in XERCES (XERCESJ-1257), we assume the XML is always UTF8, so we simply provide reader.
reader.Parse(new InputSource(IOUtils.GetDecodingReader(localFileIS, Encoding.UTF8)));
}
- catch (IOException /*ioe*/)
+ catch (Exception ioe) when (ioe.IsIOException())
{
lock (outerInstance)
{
@@ -241,11 +229,11 @@ public void Run()
}
catch (SAXException sae)
{
- throw new Exception(sae.ToString(), sae);
+ throw RuntimeException.Create(sae);
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new Exception(ioe.ToString(), ioe);
+ throw RuntimeException.Create(ioe);
}
finally
{
diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/EnwikiQueryMaker.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/EnwikiQueryMaker.cs
index 8967321418..b27faee173 100644
--- a/src/Lucene.Net.Benchmark/ByTask/Feeds/EnwikiQueryMaker.cs
+++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/EnwikiQueryMaker.cs
@@ -120,9 +120,9 @@ private static Query[] CreateQueries(IList
public static TopFieldDocs Search(IndexSearcher searcher, Query q, Filter filter, int n, Sort sort, bool doDocScores, bool doMaxScore, ICollector fc)
{
- if (sort == null)
+ if (sort is null)
{
- throw new ArgumentException("sort must not be null");
+ throw new ArgumentNullException(nameof(sort), "sort must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
return (TopFieldDocs)DoSearch(searcher, null, q, filter, n, sort, doDocScores, doMaxScore, fc);
}
@@ -281,9 +281,9 @@ public static TopDocs SearchAfter(IndexSearcher searcher, ScoreDoc after, Query
///
public static TopDocs SearchAfter(IndexSearcher searcher, ScoreDoc after, Query q, Filter filter, int n, Sort sort, ICollector fc)
{
- if (sort == null)
+ if (sort is null)
{
- throw new ArgumentException("sort must not be null");
+ throw new ArgumentNullException(nameof(sort), "sort must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
return DoSearch(searcher, after, q, filter, n, sort, false, false, fc);
}
@@ -294,9 +294,9 @@ public static TopDocs SearchAfter(IndexSearcher searcher, ScoreDoc after, Query
///
public static TopDocs SearchAfter(IndexSearcher searcher, ScoreDoc after, Query q, Filter filter, int n, Sort sort, bool doDocScores, bool doMaxScore, ICollector fc)
{
- if (sort == null)
+ if (sort is null)
{
- throw new ArgumentException("sort must not be null");
+ throw new ArgumentNullException(nameof(sort), "sort must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
return DoSearch(searcher, after, q, filter, n, sort, doDocScores, doMaxScore, fc);
}
diff --git a/src/Lucene.Net.Facet/RandomSamplingFacetsCollector.cs b/src/Lucene.Net.Facet/RandomSamplingFacetsCollector.cs
index 91a63667e8..8bd0fcc191 100644
--- a/src/Lucene.Net.Facet/RandomSamplingFacetsCollector.cs
+++ b/src/Lucene.Net.Facet/RandomSamplingFacetsCollector.cs
@@ -258,9 +258,9 @@ private MatchingDocs CreateSample(MatchingDocs docs)
return new MatchingDocs(docs.Context, sampleDocs, docs.TotalHits, null);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
diff --git a/src/Lucene.Net.Facet/Range/DoubleRange.cs b/src/Lucene.Net.Facet/Range/DoubleRange.cs
index 606415fdd4..eb42e8034e 100644
--- a/src/Lucene.Net.Facet/Range/DoubleRange.cs
+++ b/src/Lucene.Net.Facet/Range/DoubleRange.cs
@@ -75,7 +75,7 @@ public DoubleRange(string label, double minIn, bool minInclusive, double maxIn,
if (double.IsNaN(Min))
{
- throw new ArgumentException("min cannot be NaN");
+ throw new ArgumentOutOfRangeException(nameof(minIn), "min cannot be NaN"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (!minInclusive)
{
@@ -84,7 +84,7 @@ public DoubleRange(string label, double minIn, bool minInclusive, double maxIn,
if (double.IsNaN(Max))
{
- throw new ArgumentException("max cannot be NaN");
+ throw new ArgumentOutOfRangeException(nameof(maxIn), "max cannot be NaN"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (!maxInclusive)
{
@@ -169,7 +169,7 @@ public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDo
fastMatchBits = dis.Bits;
if (fastMatchBits == null)
{
- throw new ArgumentException("fastMatchFilter does not implement DocIdSet.bits");
+ throw new ArgumentException("fastMatchFilter does not implement DocIdSet.Bits");
}
}
else
@@ -227,7 +227,7 @@ public virtual bool Get(int docID)
public override DocIdSetIterator GetIterator()
{
- throw new NotSupportedException("this filter can only be accessed via bits()");
+ throw UnsupportedOperationException.Create("this filter can only be accessed via Bits");
}
}
}
diff --git a/src/Lucene.Net.Facet/Range/DoubleRangeFacetCounts.cs b/src/Lucene.Net.Facet/Range/DoubleRangeFacetCounts.cs
index 4a5f18f294..5b07850620 100644
--- a/src/Lucene.Net.Facet/Range/DoubleRangeFacetCounts.cs
+++ b/src/Lucene.Net.Facet/Range/DoubleRangeFacetCounts.cs
@@ -117,7 +117,7 @@ private void Count(ValueSource valueSource, IEnumerable matchingDo
bits = dis.Bits;
if (bits == null)
{
- throw new ArgumentException("fastMatchFilter does not implement DocIdSet.bits");
+ throw new ArgumentException("fastMatchFilter does not implement DocIdSet.Bits");
}
}
else
diff --git a/src/Lucene.Net.Facet/Range/LongRange.cs b/src/Lucene.Net.Facet/Range/LongRange.cs
index 026cb0d481..1c71b620c3 100644
--- a/src/Lucene.Net.Facet/Range/LongRange.cs
+++ b/src/Lucene.Net.Facet/Range/LongRange.cs
@@ -164,7 +164,7 @@ public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDo
fastMatchBits = dis.Bits;
if (fastMatchBits == null)
{
- throw new ArgumentException("fastMatchFilter does not implement DocIdSet.bits");
+ throw new ArgumentException("fastMatchFilter does not implement DocIdSet.Bits");
}
}
else
@@ -224,7 +224,7 @@ public virtual bool Get(int docID)
public override DocIdSetIterator GetIterator()
{
- throw new NotSupportedException("this filter can only be accessed via bits()");
+ throw UnsupportedOperationException.Create("this filter can only be accessed via Bits");
}
}
}
diff --git a/src/Lucene.Net.Facet/Range/LongRangeFacetCounts.cs b/src/Lucene.Net.Facet/Range/LongRangeFacetCounts.cs
index 485f1c6de1..3507ab0d4f 100644
--- a/src/Lucene.Net.Facet/Range/LongRangeFacetCounts.cs
+++ b/src/Lucene.Net.Facet/Range/LongRangeFacetCounts.cs
@@ -104,7 +104,7 @@ private void Count(ValueSource valueSource, IList matchingDocs)
bits = dis.Bits;
if (bits == null)
{
- throw new ArgumentException("fastMatchFilter does not implement DocIdSet.bits");
+ throw new ArgumentException("fastMatchFilter does not implement DocIdSet.Bits");
}
}
else
diff --git a/src/Lucene.Net.Facet/Range/Range.cs b/src/Lucene.Net.Facet/Range/Range.cs
index 745d7fe232..a198021915 100644
--- a/src/Lucene.Net.Facet/Range/Range.cs
+++ b/src/Lucene.Net.Facet/Range/Range.cs
@@ -38,7 +38,7 @@ public abstract class Range
/// Sole constructor.
protected Range(string label)
{
- this.Label = label ?? throw new ArgumentNullException(nameof(label));
+ this.Label = label ?? throw new ArgumentNullException(nameof(label)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
///
diff --git a/src/Lucene.Net.Facet/Range/RangeFacetCounts.cs b/src/Lucene.Net.Facet/Range/RangeFacetCounts.cs
index bd44fa8c0a..af9a7cdf03 100644
--- a/src/Lucene.Net.Facet/Range/RangeFacetCounts.cs
+++ b/src/Lucene.Net.Facet/Range/RangeFacetCounts.cs
@@ -72,7 +72,7 @@ public override FacetResult GetTopChildren(int topN, string dim, params string[]
}
if (path.Length != 0)
{
- throw new ArgumentException("path.length should be 0");
+ throw new ArgumentException("path.Length should be 0");
}
LabelAndValue[] labelValues = new LabelAndValue[m_counts.Length];
for (int i = 0; i < m_counts.Length; i++)
@@ -85,7 +85,7 @@ public override FacetResult GetTopChildren(int topN, string dim, params string[]
public override float GetSpecificValue(string dim, params string[] path)
{
// TODO: should we impl this?
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override IList GetAllDims(int topN)
diff --git a/src/Lucene.Net.Facet/SortedSet/SortedSetDocValuesFacetCounts.cs b/src/Lucene.Net.Facet/SortedSet/SortedSetDocValuesFacetCounts.cs
index 14ae716afd..77ca2ef531 100644
--- a/src/Lucene.Net.Facet/SortedSet/SortedSetDocValuesFacetCounts.cs
+++ b/src/Lucene.Net.Facet/SortedSet/SortedSetDocValuesFacetCounts.cs
@@ -77,11 +77,11 @@ public override FacetResult GetTopChildren(int topN, string dim, params string[]
{
if (topN <= 0)
{
- throw new ArgumentException("topN must be > 0 (got: " + topN + ")");
+ throw new ArgumentOutOfRangeException(nameof(topN), "topN must be > 0 (got: " + topN + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (path.Length > 0)
{
- throw new ArgumentException("path should be 0 length");
+ throw new ArgumentOutOfRangeException(nameof(path), "path should be 0 length"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
OrdRange ordRange = state.GetOrdRange(dim);
if (ordRange == null)
@@ -177,7 +177,7 @@ private void Count(IList matchingDocs)
// AIOOBE can happen:
if (!Equals(ReaderUtil.GetTopLevelContext(hits.Context).Reader, origReader))
{
- throw new InvalidOperationException("the SortedSetDocValuesReaderState provided to this class does not match the reader being searched; you must create a new SortedSetDocValuesReaderState every time you open a new IndexReader");
+ throw IllegalStateException.Create("the SortedSetDocValuesReaderState provided to this class does not match the reader being searched; you must create a new SortedSetDocValuesReaderState every time you open a new IndexReader");
}
SortedSetDocValues segValues = reader.GetSortedSetDocValues(field);
@@ -276,7 +276,7 @@ public override float GetSpecificValue(string dim, params string[] path)
{
if (path.Length != 1)
{
- throw new ArgumentException("path must be length=1");
+ throw new ArgumentException("path must be Length=1");
}
int ord = (int)dv.LookupTerm(new BytesRef(FacetsConfig.PathToString(dim, path)));
if (ord < 0)
diff --git a/src/Lucene.Net.Facet/Taxonomy/CachedOrdinalsReader.cs b/src/Lucene.Net.Facet/Taxonomy/CachedOrdinalsReader.cs
index fa8760738b..e7a2dd5992 100644
--- a/src/Lucene.Net.Facet/Taxonomy/CachedOrdinalsReader.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/CachedOrdinalsReader.cs
@@ -164,7 +164,7 @@ public CachedOrds(OrdinalsSegmentReader source, int maxDoc)
{
if (nextLength > ArrayUtil.MAX_ARRAY_LENGTH)
{
- throw new ThreadStateException("too many ordinals (>= " + nextLength + ") to cache");
+ throw IllegalStateException.Create("too many ordinals (>= " + nextLength + ") to cache");
}
ords = ArrayUtil.Grow(ords, (int)nextLength);
}
diff --git a/src/Lucene.Net.Facet/Taxonomy/Directory/DirectoryTaxonomyReader.cs b/src/Lucene.Net.Facet/Taxonomy/Directory/DirectoryTaxonomyReader.cs
index 91f6a81d46..f919a985d6 100644
--- a/src/Lucene.Net.Facet/Taxonomy/Directory/DirectoryTaxonomyReader.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/Directory/DirectoryTaxonomyReader.cs
@@ -469,7 +469,7 @@ public virtual string ToString(int max)
}
sb.Append(i + ": " + category.ToString() + "\n");
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
// LUCENENET TODO: Should we use a 3rd party logging library?
diff --git a/src/Lucene.Net.Facet/Taxonomy/Directory/DirectoryTaxonomyWriter.cs b/src/Lucene.Net.Facet/Taxonomy/Directory/DirectoryTaxonomyWriter.cs
index cba71c90ce..e15c06a727 100644
--- a/src/Lucene.Net.Facet/Taxonomy/Directory/DirectoryTaxonomyWriter.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/Directory/DirectoryTaxonomyWriter.cs
@@ -556,7 +556,7 @@ protected void EnsureOpen()
{
if (isClosed)
{
- throw new ObjectDisposedException(this.GetType().FullName, "The taxonomy writer has already been closed");
+ throw AlreadyClosedException.Create(this.GetType().FullName, "The taxonomy writer has already been disposed.");
}
}
@@ -897,9 +897,11 @@ public virtual int GetParent(int ordinal)
// for the parent of a nonexistant category - even if the parent array
// was allocated bigger than it really needs to be.
if (ordinal >= nextID)
- {
- throw new IndexOutOfRangeException("requested ordinal is bigger than the largest ordinal in the taxonomy");
- }
+ // LUCENENET specific: Changed exception type thrown to be consistent with guard clauses in .NET
+ throw new ArgumentOutOfRangeException(nameof(ordinal), "requested ordinal is bigger than the largest ordinal in the taxonomy");
+ // LUCENENET specific: Added additional check to defend against throwing IndexOutOfRangeException
+ if (ordinal < 0)
+ throw new ArgumentOutOfRangeException(nameof(ordinal), "ordinal may not be negative.");
int[] parents = GetTaxoArrays().Parents;
if (Debugging.AssertsEnabled) Debugging.Assert(ordinal < parents.Length, "requested ordinal ({0}); parents.length ({1}) !", ordinal, parents.Length);
diff --git a/src/Lucene.Net.Facet/Taxonomy/FloatTaxonomyFacets.cs b/src/Lucene.Net.Facet/Taxonomy/FloatTaxonomyFacets.cs
index cbe9fe18a8..56ed487f95 100644
--- a/src/Lucene.Net.Facet/Taxonomy/FloatTaxonomyFacets.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/FloatTaxonomyFacets.cs
@@ -108,7 +108,7 @@ public override FacetResult GetTopChildren(int topN, string dim, params string[]
{
if (topN <= 0)
{
- throw new ArgumentException("topN must be > 0 (got: " + topN + ")");
+ throw new ArgumentOutOfRangeException(nameof(topN), "topN must be > 0 (got: " + topN + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
FacetsConfig.DimConfig dimConfig = VerifyDim(dim);
FacetLabel cp = new FacetLabel(dim, path);
diff --git a/src/Lucene.Net.Facet/Taxonomy/IntTaxonomyFacets.cs b/src/Lucene.Net.Facet/Taxonomy/IntTaxonomyFacets.cs
index a801681a20..3980f3530e 100644
--- a/src/Lucene.Net.Facet/Taxonomy/IntTaxonomyFacets.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/IntTaxonomyFacets.cs
@@ -110,7 +110,7 @@ public override FacetResult GetTopChildren(int topN, string dim, params string[]
{
if (topN <= 0)
{
- throw new ArgumentException("topN must be > 0 (got: " + topN + ")");
+ throw new ArgumentOutOfRangeException(nameof(topN), "topN must be > 0 (got: " + topN + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
var dimConfig = VerifyDim(dim);
FacetLabel cp = new FacetLabel(dim, path);
diff --git a/src/Lucene.Net.Facet/Taxonomy/LRUHashMap.cs b/src/Lucene.Net.Facet/Taxonomy/LRUHashMap.cs
index cdc7230070..acd001c124 100644
--- a/src/Lucene.Net.Facet/Taxonomy/LRUHashMap.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/LRUHashMap.cs
@@ -110,7 +110,7 @@ public virtual int Limit
{
if (value < 1)
{
- throw new ArgumentOutOfRangeException("Limit must be at least 1");
+ throw new ArgumentOutOfRangeException("Limit must be at least 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
cache.Limit = value;
}
diff --git a/src/Lucene.Net.Facet/Taxonomy/SearcherTaxonomyManager.cs b/src/Lucene.Net.Facet/Taxonomy/SearcherTaxonomyManager.cs
index 8a5f82d664..39781da53c 100644
--- a/src/Lucene.Net.Facet/Taxonomy/SearcherTaxonomyManager.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/SearcherTaxonomyManager.cs
@@ -167,7 +167,7 @@ protected override SearcherAndTaxonomy RefreshIfNeeded(SearcherAndTaxonomy @ref)
else if (taxoWriter != null && taxoWriter.TaxonomyEpoch != taxoEpoch)
{
IOUtils.Dispose(newReader, tr);
- throw new InvalidOperationException("DirectoryTaxonomyWriter.replaceTaxonomy was called, which is not allowed when using SearcherTaxonomyManager");
+ throw IllegalStateException.Create("DirectoryTaxonomyWriter.ReplaceTaxonomy() was called, which is not allowed when using SearcherTaxonomyManager");
}
return new SearcherAndTaxonomy(SearcherManager.GetSearcher(searcherFactory, newReader), tr);
diff --git a/src/Lucene.Net.Facet/Taxonomy/TaxonomyFacetSumValueSource.cs b/src/Lucene.Net.Facet/Taxonomy/TaxonomyFacetSumValueSource.cs
index 46ef005e5a..c8a0d09ac6 100644
--- a/src/Lucene.Net.Facet/Taxonomy/TaxonomyFacetSumValueSource.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/TaxonomyFacetSumValueSource.cs
@@ -83,27 +83,27 @@ public override float GetScore()
{
return score;
}
- public override int Freq => throw new NotSupportedException();
+ public override int Freq => throw UnsupportedOperationException.Create();
public override int DocID => docID;
public override int NextDoc()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override int Advance(int target)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override long GetCost()
{
return 0;
}
- public override Weight Weight => throw new NotSupportedException();
+ public override Weight Weight => throw UnsupportedOperationException.Create();
public override ICollection GetChildren()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
@@ -165,7 +165,7 @@ public override FunctionValues GetValues(IDictionary context, AtomicReaderContex
Scorer scorer = (Scorer)context["scorer"];
if (scorer == null)
{
- throw new ThreadStateException("scores are missing; be sure to pass keepScores=true to FacetsCollector");
+ throw IllegalStateException.Create("scores are missing; be sure to pass keepScores=true to FacetsCollector");
}
return new DoubleDocValuesAnonymousClass(this, scorer);
}
@@ -186,9 +186,9 @@ public override double DoubleVal(int document)
{
return scorer.GetScore();
}
- catch (IOException exception)
+ catch (Exception exception) when (exception.IsIOException())
{
- throw new Exception(exception.ToString(), exception);
+ throw RuntimeException.Create(exception);
}
}
}
diff --git a/src/Lucene.Net.Facet/Taxonomy/TaxonomyReader.cs b/src/Lucene.Net.Facet/Taxonomy/TaxonomyReader.cs
index 3a82084b18..556faaf0ba 100644
--- a/src/Lucene.Net.Facet/Taxonomy/TaxonomyReader.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/TaxonomyReader.cs
@@ -171,7 +171,7 @@ protected void EnsureOpen()
{
if (RefCount <= 0)
{
- throw new ObjectDisposedException(this.GetType().FullName, "this TaxonomyReader is closed");
+ throw AlreadyClosedException.Create(this.GetType().FullName, "this TaxonomyReader is disposed.");
}
}
@@ -225,7 +225,7 @@ public void DecRef()
}
else if (rc < 0)
{
- throw new ThreadStateException("too many decRef calls: refCount is " + rc + " after decrement");
+ throw IllegalStateException.Create("too many decRef calls: refCount is " + rc + " after decrement");
}
}
diff --git a/src/Lucene.Net.Facet/Taxonomy/TaxonomyWriter.cs b/src/Lucene.Net.Facet/Taxonomy/TaxonomyWriter.cs
index 89d41fd8ff..4d5bbb887f 100644
--- a/src/Lucene.Net.Facet/Taxonomy/TaxonomyWriter.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/TaxonomyWriter.cs
@@ -85,7 +85,7 @@ public interface ITaxonomyWriter : IDisposable, ITwoPhaseCommit
/// If the given ordinal is a top-level category, the
/// is returned.
/// If an invalid ordinal is given (negative or beyond the last available
- /// ordinal), an is thrown. However, it is
+ /// ordinal), an is thrown. However, it is
/// expected that will only be called for ordinals which are
/// already known to be in the taxonomy.
///
diff --git a/src/Lucene.Net.Facet/Taxonomy/WriterCache/CollisionMap.cs b/src/Lucene.Net.Facet/Taxonomy/WriterCache/CollisionMap.cs
index d4cf6184d7..168f790832 100644
--- a/src/Lucene.Net.Facet/Taxonomy/WriterCache/CollisionMap.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/WriterCache/CollisionMap.cs
@@ -243,7 +243,7 @@ public Entry Next()
Entry e = this.next;
if (e == null)
{
- throw new InvalidOperationException(this.GetType() + " cannot get next entry"); ;
+ throw IllegalStateException.Create(this.GetType() + " cannot get next entry"); ;
}
Entry n = e.next;
@@ -261,7 +261,7 @@ public Entry Next()
// LUCENENET specific - .NET doesn't support Remove() anyway, so we can nix this
//public void Remove()
//{
- // throw new NotSupportedException();
+ // throw UnsupportedOperationException.Create();
//}
public void Dispose()
diff --git a/src/Lucene.Net.Facet/Taxonomy/WriterCache/NameIntCacheLRU.cs b/src/Lucene.Net.Facet/Taxonomy/WriterCache/NameIntCacheLRU.cs
index da1eddcbaf..b17e5c7178 100644
--- a/src/Lucene.Net.Facet/Taxonomy/WriterCache/NameIntCacheLRU.cs
+++ b/src/Lucene.Net.Facet/Taxonomy/WriterCache/NameIntCacheLRU.cs
@@ -137,8 +137,8 @@ internal sealed class NameCacheLru : IInternalNameInt32CacheLru
internal NameCacheLru(int limit, Func getKey, Func getKeyWithPrefixLength)
{
- this.getKey = getKey ?? throw new ArgumentNullException(nameof(getKey));
- this.getKeyWithPrefixLength = getKeyWithPrefixLength ?? throw new ArgumentNullException(nameof(getKeyWithPrefixLength));
+ this.getKey = getKey ?? throw new ArgumentNullException(nameof(getKey)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
+ this.getKeyWithPrefixLength = getKeyWithPrefixLength ?? throw new ArgumentNullException(nameof(getKeyWithPrefixLength)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
this.maxCacheSize = limit;
CreateCache(limit);
}
diff --git a/src/Lucene.Net.Grouping/AbstractFirstPassGroupingCollector.cs b/src/Lucene.Net.Grouping/AbstractFirstPassGroupingCollector.cs
index e6bacdea59..f9fca90fa9 100644
--- a/src/Lucene.Net.Grouping/AbstractFirstPassGroupingCollector.cs
+++ b/src/Lucene.Net.Grouping/AbstractFirstPassGroupingCollector.cs
@@ -71,7 +71,7 @@ protected AbstractFirstPassGroupingCollector(Sort groupSort, int topNGroups) //
{
if (topNGroups < 1)
{
- throw new ArgumentException("topNGroups must be >= 1 (got " + topNGroups + ")");
+ throw new ArgumentOutOfRangeException("topNGroups must be >= 1 (got " + topNGroups + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
// TODO: allow null groupSort to mean "by relevance",
@@ -112,7 +112,7 @@ public virtual IEnumerable> GetTopGroups(int groupOffs
if (groupOffset < 0)
{
- throw new ArgumentException("groupOffset must be >= 0 (got " + groupOffset + ")");
+ throw new ArgumentOutOfRangeException("groupOffset must be >= 0 (got " + groupOffset + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (groupMap.Count <= groupOffset)
diff --git a/src/Lucene.Net.Grouping/AbstractSecondPassGroupingCollector.cs b/src/Lucene.Net.Grouping/AbstractSecondPassGroupingCollector.cs
index b29da15a45..d571c773d4 100644
--- a/src/Lucene.Net.Grouping/AbstractSecondPassGroupingCollector.cs
+++ b/src/Lucene.Net.Grouping/AbstractSecondPassGroupingCollector.cs
@@ -56,7 +56,7 @@ protected AbstractSecondPassGroupingCollector(IEnumerable throw new InvalidOperationException(); // TODO: wtf does this class do?
+ public override int Freq => throw UnsupportedOperationException.Create(); // TODO: wtf does this class do?
public override int DocID => doc;
public override int Advance(int target)
{
- throw new InvalidOperationException();
+ throw UnsupportedOperationException.Create();
}
public override int NextDoc()
{
- throw new InvalidOperationException();
+ throw UnsupportedOperationException.Create();
}
public override long GetCost()
@@ -119,11 +119,11 @@ public override long GetCost()
return 1;
}
- public override Weight Weight => throw new InvalidOperationException();
+ public override Weight Weight => throw UnsupportedOperationException.Create();
public override ICollection GetChildren()
{
- throw new InvalidOperationException();
+ throw UnsupportedOperationException.Create();
}
}
@@ -279,7 +279,7 @@ public BlockGroupingCollector(Sort groupSort, int topNGroups, bool needsScores,
if (topNGroups < 1)
{
- throw new ArgumentException("topNGroups must be >= 1 (got " + topNGroups + ")");
+ throw new ArgumentOutOfRangeException(nameof(topNGroups), "topNGroups must be >= 1 (got " + topNGroups + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
groupQueue = new GroupQueue(this, topNGroups);
diff --git a/src/Lucene.Net.Grouping/GroupingSearch.cs b/src/Lucene.Net.Grouping/GroupingSearch.cs
index a0c7d15bb2..ccf977efa0 100644
--- a/src/Lucene.Net.Grouping/GroupingSearch.cs
+++ b/src/Lucene.Net.Grouping/GroupingSearch.cs
@@ -156,7 +156,7 @@ public virtual ITopGroups Search(IndexSearcher searcher, Filter filter,
}
else
{
- throw new InvalidOperationException("Either groupField, groupFunction or groupEndDocs must be set."); // This can't happen...
+ throw IllegalStateException.Create("Either groupField, groupFunction or groupEndDocs must be set."); // This can't happen...
}
}
@@ -183,7 +183,7 @@ public virtual ITopGroups Search(IndexSearcher searche
}
else
{
- throw new InvalidOperationException("Either groupField, groupFunction or groupEndDocs must be set."); // This can't happen...
+ throw IllegalStateException.Create("Either groupField, groupFunction or groupEndDocs must be set."); // This can't happen...
}
}
diff --git a/src/Lucene.Net.Highlighter/Highlight/GradientFormatter.cs b/src/Lucene.Net.Highlighter/Highlight/GradientFormatter.cs
index 09eabd712e..ba8e60beb0 100644
--- a/src/Lucene.Net.Highlighter/Highlight/GradientFormatter.cs
+++ b/src/Lucene.Net.Highlighter/Highlight/GradientFormatter.cs
@@ -204,7 +204,7 @@ public static int HexToInt32(string hex)
{
int len = hex.Length;
if (len > 16)
- throw new FormatException();
+ throw NumberFormatException.Create();
try
{
@@ -217,7 +217,7 @@ public static int HexToInt32(string hex)
}
catch (ArgumentException e)
{
- throw new FormatException(e.Message, e);
+ throw NumberFormatException.Create(e);
}
}
}
diff --git a/src/Lucene.Net.Highlighter/Highlight/Highlighter.cs b/src/Lucene.Net.Highlighter/Highlight/Highlighter.cs
index d6cb282f13..1d1a0a052f 100644
--- a/src/Lucene.Net.Highlighter/Highlight/Highlighter.cs
+++ b/src/Lucene.Net.Highlighter/Highlight/Highlighter.cs
@@ -329,7 +329,7 @@ public TextFragment[] GetBestTextFragments(
tokenStream.End();
tokenStream.Dispose();
}
- catch (Exception)
+ catch (Exception e) when (e.IsException())
{
}
}
diff --git a/src/Lucene.Net.Highlighter/Highlight/QueryTermExtractor.cs b/src/Lucene.Net.Highlighter/Highlight/QueryTermExtractor.cs
index 946852351b..f0d152217f 100644
--- a/src/Lucene.Net.Highlighter/Highlight/QueryTermExtractor.cs
+++ b/src/Lucene.Net.Highlighter/Highlight/QueryTermExtractor.cs
@@ -65,7 +65,7 @@ public static WeightedTerm[] GetIdfWeightedTerms(Query query, IndexReader reader
var idf = (float)(Math.Log((float)totalNumDocs / (double)(docFreq + 1)) + 1.0);
t.Weight *= idf;
}
- catch (IOException)
+ catch (Exception e) when (e.IsIOException())
{
//ignore
}
@@ -122,7 +122,7 @@ private static void GetTerms(Query query, ISet terms, bool prohibi
}
}
}
- catch (NotSupportedException) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception ignore) when (ignore.IsUnsupportedOperationException())
{
//this is non-fatal for our purposes
}
diff --git a/src/Lucene.Net.Highlighter/Highlight/TokenSources.cs b/src/Lucene.Net.Highlighter/Highlight/TokenSources.cs
index bc9cd26aff..db98f19cae 100644
--- a/src/Lucene.Net.Highlighter/Highlight/TokenSources.cs
+++ b/src/Lucene.Net.Highlighter/Highlight/TokenSources.cs
@@ -341,9 +341,9 @@ public static TokenStream GetTokenStream(string field, string contents,
{
return analyzer.GetTokenStream(field, contents);
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
- throw new Exception(ex.ToString(), ex);
+ throw RuntimeException.Create(ex);
}
}
}
diff --git a/src/Lucene.Net.Highlighter/Highlight/WeightedSpanTermExtractor.cs b/src/Lucene.Net.Highlighter/Highlight/WeightedSpanTermExtractor.cs
index cec91d8bee..458f794c9a 100644
--- a/src/Lucene.Net.Highlighter/Highlight/WeightedSpanTermExtractor.cs
+++ b/src/Lucene.Net.Highlighter/Highlight/WeightedSpanTermExtractor.cs
@@ -399,7 +399,7 @@ internal sealed class DelegatingAtomicReader : FilterAtomicReader
internal DelegatingAtomicReader(AtomicReader reader) : base(reader) { }
- public override FieldInfos FieldInfos => throw new NotSupportedException();
+ public override FieldInfos FieldInfos => throw UnsupportedOperationException.Create();
public override Fields Fields => new DelegatingFilterFields(base.Fields);
diff --git a/src/Lucene.Net.Highlighter/PostingsHighlight/DefaultPassageFormatter.cs b/src/Lucene.Net.Highlighter/PostingsHighlight/DefaultPassageFormatter.cs
index 35d01c4cbb..5bc7829bfa 100644
--- a/src/Lucene.Net.Highlighter/PostingsHighlight/DefaultPassageFormatter.cs
+++ b/src/Lucene.Net.Highlighter/PostingsHighlight/DefaultPassageFormatter.cs
@@ -55,13 +55,10 @@ public DefaultPassageFormatter()
/// true if text should be html-escaped
public DefaultPassageFormatter(string preTag, string postTag, string ellipsis, bool escape)
{
- if (preTag == null || postTag == null || ellipsis == null)
- {
- throw new ArgumentException(); //throw new NullPointerException();
- }
- this.m_preTag = preTag;
- this.m_postTag = postTag;
- this.m_ellipsis = ellipsis;
+ // LUCENENET specific - changed from NullPointerException to ArgumentNullException (.NET convention)
+ this.m_preTag = preTag ?? throw new ArgumentNullException(nameof(preTag));
+ this.m_postTag = postTag ?? throw new ArgumentNullException(nameof(postTag));
+ this.m_ellipsis = ellipsis ?? throw new ArgumentNullException(nameof(ellipsis));
this.m_escape = escape;
}
diff --git a/src/Lucene.Net.Highlighter/PostingsHighlight/MultiTermHighlighting.cs b/src/Lucene.Net.Highlighter/PostingsHighlight/MultiTermHighlighting.cs
index fc83d5c027..e9c8c85164 100644
--- a/src/Lucene.Net.Highlighter/PostingsHighlight/MultiTermHighlighting.cs
+++ b/src/Lucene.Net.Highlighter/PostingsHighlight/MultiTermHighlighting.cs
@@ -320,7 +320,7 @@ public override BytesRef GetPayload()
public override int NextDoc()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override int Advance(int target)
diff --git a/src/Lucene.Net.Highlighter/PostingsHighlight/PostingsHighlighter.cs b/src/Lucene.Net.Highlighter/PostingsHighlight/PostingsHighlighter.cs
index 316dd52dfe..f5654dab51 100644
--- a/src/Lucene.Net.Highlighter/PostingsHighlight/PostingsHighlighter.cs
+++ b/src/Lucene.Net.Highlighter/PostingsHighlight/PostingsHighlighter.cs
@@ -128,11 +128,15 @@ public ICUPostingsHighlighter()
/// if is negative or int.MaxValue
public ICUPostingsHighlighter(int maxLength)
{
- if (maxLength < 0 || maxLength == int.MaxValue)
+ if (maxLength < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(maxLength), "maxLength must be >= 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
+ }
+ if (maxLength == int.MaxValue)
{
// two reasons: no overflow problems in BreakIterator.preceding(offset+1),
// our sentinel in the offsets queue uses this value to terminate.
- throw new ArgumentException("maxLength must be < System.Int32.MaxValue");
+ throw new ArgumentOutOfRangeException(nameof(maxLength), "maxLength must be < System.Int32.MaxValue"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.maxLength = maxLength;
}
@@ -381,6 +385,18 @@ protected override int Compare(int i, int j)
/// if field was indexed without
protected internal virtual IDictionary HighlightFieldsAsObjects(string[] fieldsIn, Query query, IndexSearcher searcher, int[] docidsIn, int[] maxPassagesIn)
{
+ // LUCENENET specific - added additional guard clauses to check for null
+ if (fieldsIn is null)
+ throw new ArgumentNullException(nameof(fieldsIn));
+ if (query is null)
+ throw new ArgumentNullException(nameof(query));
+ if (searcher is null)
+ throw new ArgumentNullException(nameof(searcher));
+ if (docidsIn is null)
+ throw new ArgumentNullException(nameof(docidsIn));
+ if (maxPassagesIn is null)
+ throw new ArgumentNullException(nameof(maxPassagesIn));
+
if (fieldsIn.Length < 1)
{
throw new ArgumentException("fieldsIn must not be empty");
@@ -503,7 +519,8 @@ private IDictionary HighlightField(string field, string[] contents,
PassageFormatter fieldFormatter = GetFormatter(field);
if (fieldFormatter == null)
{
- throw new NullReferenceException("PassageFormatter cannot be null");
+ // LUCENENET: Changed from NullPointerException to InvalidOperationException (which isn't caught anywhere outside of tests)
+ throw IllegalStateException.Create("PassageFormatter cannot be null");
}
// check if we should do any multiterm processing
@@ -594,7 +611,8 @@ private Passage[] HighlightDoc(string field, BytesRef[] terms, int contentLength
PassageScorer scorer = GetScorer(field);
if (scorer == null)
{
- throw new NullReferenceException("PassageScorer cannot be null");
+ // LUCENENET: Changed from NullPointerException to InvalidOperationException (which isn't caught anywhere outside of tests)
+ throw IllegalStateException.Create("PassageScorer cannot be null");
}
JCG.PriorityQueue pq = new JCG.PriorityQueue();
float[] weights = new float[terms.Length];
@@ -812,9 +830,9 @@ public virtual int CompareTo(OffsetsEnum other)
return off.CompareTo(otherOff);
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
}
diff --git a/src/Lucene.Net.Highlighter/PostingsHighlight/WholeBreakIterator.cs b/src/Lucene.Net.Highlighter/PostingsHighlight/WholeBreakIterator.cs
index e96719f228..90a7028b71 100644
--- a/src/Lucene.Net.Highlighter/PostingsHighlight/WholeBreakIterator.cs
+++ b/src/Lucene.Net.Highlighter/PostingsHighlight/WholeBreakIterator.cs
@@ -41,7 +41,7 @@ public override int Following(int pos)
{
if (pos < start || pos > end)
{
- throw new ArgumentException("offset out of bounds");
+ throw new ArgumentOutOfRangeException(nameof(pos), "offset out of bounds"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
else if (pos == end)
{
@@ -98,7 +98,7 @@ public override int Preceding(int pos)
{
if (pos < start || pos > end)
{
- throw new ArgumentException("offset out of bounds");
+ throw new ArgumentOutOfRangeException(nameof(pos), "offset out of bounds"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
else if (pos == start)
{
@@ -125,19 +125,21 @@ public override int Previous()
}
}
- public override bool IsBoundary(int offset)
- {
- if (offset == 0)
- {
- return true;
- }
- int boundary = Following(offset - 1);
- if (boundary == Done)
- {
- throw new ArgumentException();
- }
- return boundary == offset;
- }
+ // LUCENENET: This method override didn't exist in Lucene 4.8.1 and it isn't clear why this was
+ // here because there were no comments.
+ //public override bool IsBoundary(int offset)
+ //{
+ // if (offset == 0)
+ // {
+ // return true;
+ // }
+ // int boundary = Following(offset - 1);
+ // if (boundary == Done)
+ // {
+ // throw new ArgumentException();
+ // }
+ // return boundary == offset;
+ //}
public override void SetText(CharacterIterator newText)
{
diff --git a/src/Lucene.Net.Highlighter/VectorHighlight/BaseFragListBuilder.cs b/src/Lucene.Net.Highlighter/VectorHighlight/BaseFragListBuilder.cs
index 944bf43fab..0ca50f9e06 100644
--- a/src/Lucene.Net.Highlighter/VectorHighlight/BaseFragListBuilder.cs
+++ b/src/Lucene.Net.Highlighter/VectorHighlight/BaseFragListBuilder.cs
@@ -37,7 +37,7 @@ public abstract class BaseFragListBuilder : IFragListBuilder
protected BaseFragListBuilder(int margin) // LUCENENET: CA1012: Abstract types should not have constructors (marked protected)
{
if (margin < 0)
- throw new ArgumentException("margin(" + margin + ") is too small. It must be 0 or higher.");
+ throw new ArgumentOutOfRangeException(nameof(margin), "margin(" + margin + ") is too small. It must be 0 or higher."); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
this.margin = margin;
this.minFragCharSize = Math.Max(1, margin * MIN_FRAG_CHAR_SIZE_FACTOR);
@@ -54,8 +54,13 @@ protected BaseFragListBuilder() // LUCENENET: CA1012: Abstract types should not
protected virtual FieldFragList CreateFieldFragList(FieldPhraseList fieldPhraseList, FieldFragList fieldFragList, int fragCharSize)
{
+ // LUCENENET specific - added guard clauses to check for nulls
+ if (fieldPhraseList is null)
+ throw new ArgumentNullException(nameof(fieldPhraseList));
+ if (fieldFragList is null)
+ throw new ArgumentNullException(nameof(fieldFragList));
if (fragCharSize < minFragCharSize)
- throw new ArgumentException("fragCharSize(" + fragCharSize + ") is too small. It must be " + minFragCharSize + " or higher.");
+ throw new ArgumentOutOfRangeException(nameof(fragCharSize), "fragCharSize(" + fragCharSize + ") is too small. It must be " + minFragCharSize + " or higher."); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
List wpil = new List();
using (IteratorQueue queue = new IteratorQueue(fieldPhraseList.PhraseList.GetEnumerator()))
@@ -130,6 +135,10 @@ protected virtual FieldFragList CreateFieldFragList(FieldPhraseList fieldPhraseL
/// true if this phrase info should be accepted as a highligh phrase
protected virtual bool AcceptPhrase(WeightedPhraseInfo info, int matchLength, int fragCharSize)
{
+ // LUCENENET specific - added guard clause to check for null
+ if (info is null)
+ throw new ArgumentNullException(nameof(WeightedPhraseInfo));
+
return info.TermsOffsets.Count <= 1 || matchLength <= fragCharSize;
}
diff --git a/src/Lucene.Net.Highlighter/VectorHighlight/BaseFragmentsBuilder.cs b/src/Lucene.Net.Highlighter/VectorHighlight/BaseFragmentsBuilder.cs
index 6cfe11abc2..a30035da11 100644
--- a/src/Lucene.Net.Highlighter/VectorHighlight/BaseFragmentsBuilder.cs
+++ b/src/Lucene.Net.Highlighter/VectorHighlight/BaseFragmentsBuilder.cs
@@ -115,9 +115,21 @@ public virtual string[] CreateFragments(IndexReader reader, int docId,
string fieldName, FieldFragList fieldFragList, int maxNumFragments,
string[] preTags, string[] postTags, IEncoder encoder)
{
+ // LUCENENET specific - added guard clauses to check for null
+ if (reader is null)
+ throw new ArgumentNullException(nameof(reader));
+ if (fieldFragList is null)
+ throw new ArgumentNullException(nameof(fieldFragList));
+ if (preTags is null)
+ throw new ArgumentNullException(nameof(preTags));
+ if (postTags is null)
+ throw new ArgumentNullException(nameof(postTags));
+ if (encoder is null)
+ throw new ArgumentNullException(nameof(encoder));
+
if (maxNumFragments < 0)
{
- throw new ArgumentException("maxNumFragments(" + maxNumFragments + ") must be positive number.");
+ throw new ArgumentOutOfRangeException(nameof(maxNumFragments), "maxNumFragments(" + maxNumFragments + ") must be positive number."); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
IList fragInfos = fieldFragList.FragInfos;
diff --git a/src/Lucene.Net.Highlighter/VectorHighlight/FastVectorHighlighter.cs b/src/Lucene.Net.Highlighter/VectorHighlight/FastVectorHighlighter.cs
index 2ae421b6bb..e5da34c9e0 100644
--- a/src/Lucene.Net.Highlighter/VectorHighlight/FastVectorHighlighter.cs
+++ b/src/Lucene.Net.Highlighter/VectorHighlight/FastVectorHighlighter.cs
@@ -83,10 +83,10 @@ public virtual FieldQuery GetFieldQuery(Query query)
{
return new FieldQuery(query, null, phraseHighlight, fieldMatch);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
// should never be thrown when reader is null
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
diff --git a/src/Lucene.Net.Highlighter/VectorHighlight/FieldQuery.cs b/src/Lucene.Net.Highlighter/VectorHighlight/FieldQuery.cs
index dc52f298c0..3e220fa373 100644
--- a/src/Lucene.Net.Highlighter/VectorHighlight/FieldQuery.cs
+++ b/src/Lucene.Net.Highlighter/VectorHighlight/FieldQuery.cs
@@ -323,7 +323,7 @@ private string GetKey(Query query)
return multiTermQuery.Field;
}
else
- throw new Exception("query \"" + query.ToString() + "\" must be flatten first.");
+ throw RuntimeException.Create("query \"" + query.ToString() + "\" must be flatten first.");
}
///
@@ -369,7 +369,7 @@ internal void SaveTerms(ICollection flatQueries, IndexReader reader)
}
}
else
- throw new Exception("query \"" + query.ToString() + "\" must be flatten first.");
+ throw RuntimeException.Create("query \"" + query.ToString() + "\" must be flatten first.");
}
}
@@ -471,7 +471,7 @@ internal void Add(Query query /*, IndexReader reader // LUCENENET: Never read */
qpm.MarkTerminal(pq.Slop, pq.Boost);
}
else
- throw new Exception("query \"" + query.ToString() + "\" must be flatten first.");
+ throw RuntimeException.Create("query \"" + query.ToString() + "\" must be flatten first.");
}
public virtual QueryPhraseMap GetTermMap(string term)
diff --git a/src/Lucene.Net.Join/FakeScorer.cs b/src/Lucene.Net.Join/FakeScorer.cs
index a089ccc54f..ea82400942 100644
--- a/src/Lucene.Net.Join/FakeScorer.cs
+++ b/src/Lucene.Net.Join/FakeScorer.cs
@@ -37,16 +37,16 @@ public FakeScorer()
public override int Advance(int target)
{
- throw new NotSupportedException("FakeScorer doesn't support Advance(int)");
+ throw UnsupportedOperationException.Create("FakeScorer doesn't support Advance(int)");
}
public override int DocID => doc;
- public override int Freq => throw new NotSupportedException("FakeScorer doesn't support Freq");
+ public override int Freq => throw UnsupportedOperationException.Create("FakeScorer doesn't support Freq");
public override int NextDoc()
{
- throw new NotSupportedException("FakeScorer doesn't support NextDoc()");
+ throw UnsupportedOperationException.Create("FakeScorer doesn't support NextDoc()");
}
public override float GetScore()
@@ -59,11 +59,11 @@ public override long GetCost()
return 1;
}
- public override Weight Weight => throw new NotSupportedException();
+ public override Weight Weight => throw UnsupportedOperationException.Create();
public override ICollection GetChildren()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
}
\ No newline at end of file
diff --git a/src/Lucene.Net.Join/ToChildBlockJoinQuery.cs b/src/Lucene.Net.Join/ToChildBlockJoinQuery.cs
index 31f3538b56..5557c5bc57 100644
--- a/src/Lucene.Net.Join/ToChildBlockJoinQuery.cs
+++ b/src/Lucene.Net.Join/ToChildBlockJoinQuery.cs
@@ -135,7 +135,7 @@ public override Scorer GetScorer(AtomicReaderContext readerContext, IBits accept
}
if (!(parents is FixedBitSet))
{
- throw new InvalidOperationException("parentFilter must return FixedBitSet; got " + parents);
+ throw IllegalStateException.Create("parentFilter must return FixedBitSet; got " + parents);
}
return new ToChildBlockJoinScorer(this, parentScorer, (FixedBitSet)parents, _doScores, acceptDocs);
@@ -144,7 +144,7 @@ public override Scorer GetScorer(AtomicReaderContext readerContext, IBits accept
public override Explanation Explain(AtomicReaderContext reader, int doc)
{
// TODO
- throw new NotSupportedException(GetType().Name + " cannot explain match on parent document");
+ throw UnsupportedOperationException.Create(GetType().Name + " cannot explain match on parent document");
}
public override bool ScoresDocsOutOfOrder => false;
@@ -265,7 +265,7 @@ private void ValidateParentDoc()
{
if (_parentDoc != NO_MORE_DOCS && !_parentBits.Get(_parentDoc))
{
- throw new InvalidOperationException(INVALID_QUERY_MESSAGE + _parentDoc);
+ throw IllegalStateException.Create(INVALID_QUERY_MESSAGE + _parentDoc);
}
}
diff --git a/src/Lucene.Net.Join/ToParentBlockJoinQuery.cs b/src/Lucene.Net.Join/ToParentBlockJoinQuery.cs
index 2517f90e11..caf4533f35 100644
--- a/src/Lucene.Net.Join/ToParentBlockJoinQuery.cs
+++ b/src/Lucene.Net.Join/ToParentBlockJoinQuery.cs
@@ -174,7 +174,7 @@ public override Scorer GetScorer(AtomicReaderContext readerContext, IBits accept
}
if (!(parents is FixedBitSet))
{
- throw new InvalidOperationException("parentFilter must return FixedBitSet; got " + parents);
+ throw IllegalStateException.Create("parentFilter must return FixedBitSet; got " + parents);
}
return new BlockJoinScorer(this, childScorer, (FixedBitSet)parents, firstChildDoc, scoreMode, acceptDocs);
@@ -245,7 +245,7 @@ internal virtual float[] SwapChildScores(float[] other)
{
if (_scoreMode == ScoreMode.None)
{
- throw new InvalidOperationException("ScoreMode is None; you must pass trackScores=false to ToParentBlockJoinCollector");
+ throw IllegalStateException.Create("ScoreMode is None; you must pass trackScores=false to ToParentBlockJoinCollector");
}
float[] ret = _pendingChildScores;
if (other == null)
@@ -280,7 +280,7 @@ public override int NextDoc()
// orthogonal:
if (_nextChildDoc == _parentDoc)
{
- throw new InvalidOperationException("child query must only match non-parent docs, but parent docID=" + _nextChildDoc + " matched childScorer=" + _childScorer.GetType());
+ throw IllegalStateException.Create("child query must only match non-parent docs, but parent docID=" + _nextChildDoc + " matched childScorer=" + _childScorer.GetType());
}
//System.out.println(" parentDoc=" + parentDoc);
@@ -300,7 +300,7 @@ public override int NextDoc()
// orthogonal:
if (_nextChildDoc == _parentDoc)
{
- throw new InvalidOperationException("child query must only match non-parent docs, but parent docID=" + _nextChildDoc + " matched childScorer=" + _childScorer.GetType());
+ throw IllegalStateException.Create("child query must only match non-parent docs, but parent docID=" + _nextChildDoc + " matched childScorer=" + _childScorer.GetType());
}
continue;
@@ -347,7 +347,7 @@ public override int NextDoc()
// orthogonal:
if (_nextChildDoc == _parentDoc)
{
- throw new InvalidOperationException("child query must only match non-parent docs, but parent docID=" + _nextChildDoc + " matched childScorer=" + _childScorer.GetType());
+ throw IllegalStateException.Create("child query must only match non-parent docs, but parent docID=" + _nextChildDoc + " matched childScorer=" + _childScorer.GetType());
}
switch (_scoreMode)
@@ -414,7 +414,7 @@ public override int Advance(int parentTarget)
// Parent & child docs are supposed to be orthogonal:
if (_nextChildDoc == _prevParentDoc)
{
- throw new InvalidOperationException("child query must only match non-parent docs, but parent docID=" + _nextChildDoc + " matched childScorer=" + _childScorer.GetType());
+ throw IllegalStateException.Create("child query must only match non-parent docs, but parent docID=" + _nextChildDoc + " matched childScorer=" + _childScorer.GetType());
}
int nd = NextDoc();
diff --git a/src/Lucene.Net.Memory/MemoryIndex.MemoryIndexReader.cs b/src/Lucene.Net.Memory/MemoryIndex.MemoryIndexReader.cs
index 6ff3c01aaa..20ea486e2e 100644
--- a/src/Lucene.Net.Memory/MemoryIndex.MemoryIndexReader.cs
+++ b/src/Lucene.Net.Memory/MemoryIndex.MemoryIndexReader.cs
@@ -145,7 +145,7 @@ public bool MoveNext()
public void Reset()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
diff --git a/src/Lucene.Net.Memory/MemoryIndex.cs b/src/Lucene.Net.Memory/MemoryIndex.cs
index f792302f39..bbad2e0523 100644
--- a/src/Lucene.Net.Memory/MemoryIndex.cs
+++ b/src/Lucene.Net.Memory/MemoryIndex.cs
@@ -234,17 +234,17 @@ internal MemoryIndex(bool storeOffsets, long maxReusedBytes)
/// the analyzer to use for tokenization
public virtual void AddField(string fieldName, string text, Analyzer analyzer)
{
- if (fieldName == null)
+ if (fieldName is null)
{
- throw new ArgumentException("fieldName must not be null");
+ throw new ArgumentNullException(nameof(fieldName), "fieldName must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
- if (text == null)
+ if (text is null)
{
- throw new ArgumentException("text must not be null");
+ throw new ArgumentNullException(nameof(text), "text must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
- if (analyzer == null)
+ if (analyzer is null)
{
- throw new ArgumentException("analyzer must not be null");
+ throw new ArgumentNullException(nameof(analyzer), "analyzer must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
TokenStream stream;
@@ -252,9 +252,9 @@ public virtual void AddField(string fieldName, string text, Analyzer analyzer)
{
stream = analyzer.GetTokenStream(fieldName, text);
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
- throw new Exception(ex.ToString(), ex);
+ throw RuntimeException.Create(ex);
}
AddField(fieldName, stream, 1.0f, analyzer.GetPositionIncrementGap(fieldName), analyzer.GetOffsetGap(fieldName));
@@ -272,9 +272,9 @@ public virtual void AddField(string fieldName, string text, Analyzer analyzer)
public virtual TokenStream KeywordTokenStream(ICollection keywords)
{
// TODO: deprecate & move this method into AnalyzerUtil?
- if (keywords == null)
+ if (keywords is null)
{
- throw new ArgumentException("keywords must not be null");
+ throw new ArgumentNullException(nameof(keywords), "keywords must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
return new TokenStreamAnonymousClass(keywords);
@@ -303,7 +303,7 @@ public override bool IncrementToken()
}
T obj = iter.Current;
- if (obj == null)
+ if (obj is null)
{
throw new ArgumentException("keyword must not be null");
}
@@ -405,17 +405,17 @@ public virtual void AddField(string fieldName, TokenStream stream, float boost,
{
try
{
- if (fieldName == null)
+ if (fieldName is null)
{
- throw new ArgumentException("fieldName must not be null");
+ throw new ArgumentNullException(nameof(fieldName), "fieldName must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
- if (stream == null)
+ if (stream is null)
{
- throw new ArgumentException("token stream must not be null");
+ throw new ArgumentNullException(nameof(stream), "token stream must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (boost <= 0.0f)
{
- throw new ArgumentException("boost factor must be greater than 0.0");
+ throw new ArgumentOutOfRangeException(nameof(boost), "boost factor must be greater than 0.0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
int numTokens = 0;
int numOverlapTokens = 0;
@@ -504,9 +504,9 @@ public virtual void AddField(string fieldName, TokenStream stream, float boost,
sortedFields = null; // invalidate sorted view, if any
}
} // can never happen
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
finally
{
@@ -517,9 +517,9 @@ public virtual void AddField(string fieldName, TokenStream stream, float boost,
stream.Dispose();
}
}
- catch (IOException e2)
+ catch (Exception e2) when (e2.IsIOException())
{
- throw new Exception(e2.ToString(), e2);
+ throw RuntimeException.Create(e2);
}
}
}
@@ -548,9 +548,9 @@ public virtual IndexSearcher CreateSearcher()
///
public virtual float Search(Query query)
{
- if (query == null)
+ if (query is null)
{
- throw new ArgumentException("query must not be null");
+ throw new ArgumentNullException(nameof(query), "query must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
IndexSearcher searcher = CreateSearcher();
@@ -561,9 +561,9 @@ public virtual float Search(Query query)
float score = scores[0];
return score;
} // can never happen (RAMDirectory)
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
finally
{
diff --git a/src/Lucene.Net.Misc/Document/LazyDocument.cs b/src/Lucene.Net.Misc/Document/LazyDocument.cs
index 8c37ccf0ac..f64d0fdae6 100644
--- a/src/Lucene.Net.Misc/Document/LazyDocument.cs
+++ b/src/Lucene.Net.Misc/Document/LazyDocument.cs
@@ -101,9 +101,9 @@ internal virtual Document GetDocument()
{
doc = reader.Document(docID, fieldNames);
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new InvalidOperationException("unable to load document", ioe);
+ throw IllegalStateException.Create("unable to load document", ioe);
}
}
return doc;
diff --git a/src/Lucene.Net.Misc/Index/CompoundFileExtractor.cs b/src/Lucene.Net.Misc/Index/CompoundFileExtractor.cs
index b361326102..e0c3480883 100644
--- a/src/Lucene.Net.Misc/Index/CompoundFileExtractor.cs
+++ b/src/Lucene.Net.Misc/Index/CompoundFileExtractor.cs
@@ -125,9 +125,9 @@ public static void Main(string[] args)
}
}
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- Console.WriteLine(ioe.ToString());
+ Console.Error.WriteLine(ioe.ToString());
//Console.Write(ioe.StackTrace);
}
finally
@@ -143,9 +143,9 @@ public static void Main(string[] args)
cfr.Dispose();
}
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- Console.WriteLine(ioe.ToString());
+ Console.Error.WriteLine(ioe.ToString());
//Console.Write(ioe.StackTrace);
}
}
diff --git a/src/Lucene.Net.Misc/Index/MultiPassIndexSplitter.cs b/src/Lucene.Net.Misc/Index/MultiPassIndexSplitter.cs
index e1b597f93d..37ec4a2dc9 100644
--- a/src/Lucene.Net.Misc/Index/MultiPassIndexSplitter.cs
+++ b/src/Lucene.Net.Misc/Index/MultiPassIndexSplitter.cs
@@ -170,7 +170,7 @@ public static void Main(string[] args)
continue;
}
}
- catch (Exception)
+ catch (Exception e) when (e.IsException())
{
Console.Error.WriteLine("Invalid input index - skipping: " + file);
continue;
diff --git a/src/Lucene.Net.Misc/Index/Sorter/BlockJoinComparatorSource.cs b/src/Lucene.Net.Misc/Index/Sorter/BlockJoinComparatorSource.cs
index 136b67f7fd..3d126ceef7 100644
--- a/src/Lucene.Net.Misc/Index/Sorter/BlockJoinComparatorSource.cs
+++ b/src/Lucene.Net.Misc/Index/Sorter/BlockJoinComparatorSource.cs
@@ -133,9 +133,9 @@ public override int Compare(int slot1, int slot2)
{
return Compare(childSlots[slot1], parentSlots[slot1], childSlots[slot2], parentSlots[slot2]);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
@@ -148,7 +148,7 @@ public override void SetBottom(int slot)
public override void SetTopValue(object value)
{
// we dont have enough information (the docid is needed)
- throw new NotSupportedException("this comparer cannot be used with deep paging");
+ throw UnsupportedOperationException.Create("this comparer cannot be used with deep paging");
}
public override int CompareBottom(int doc)
@@ -159,7 +159,7 @@ public override int CompareBottom(int doc)
public override int CompareTop(int doc)
{
// we dont have enough information (the docid is needed)
- throw new NotSupportedException("this comparer cannot be used with deep paging");
+ throw UnsupportedOperationException.Create("this comparer cannot be used with deep paging");
}
public override void Copy(int slot, int doc)
@@ -174,11 +174,11 @@ public override FieldComparer SetNextReader(AtomicReaderContext context)
DocIdSet parents = outerInstance.parentsFilter.GetDocIdSet(context, null);
if (parents == null)
{
- throw new InvalidOperationException("AtomicReader " + context.AtomicReader + " contains no parents!");
+ throw IllegalStateException.Create("AtomicReader " + context.AtomicReader + " contains no parents!");
}
if (!(parents is FixedBitSet))
{
- throw new InvalidOperationException("parentFilter must return FixedBitSet; got " + parents);
+ throw IllegalStateException.Create("parentFilter must return FixedBitSet; got " + parents);
}
parentBits = (FixedBitSet)parents;
for (int i = 0; i < parentComparers.Length; i++)
@@ -195,7 +195,7 @@ public override FieldComparer SetNextReader(AtomicReaderContext context)
// LUCENENET NOTE: This was value(int) in Lucene.
public override IComparable this[int slot] => throw
// really our sort "value" is more complex...
- new NotSupportedException("filling sort field values is not yet supported");
+ UnsupportedOperationException.Create("filling sort field values is not yet supported");
public override void SetScorer(Scorer scorer)
{
diff --git a/src/Lucene.Net.Misc/Index/Sorter/EarlyTerminatingSortingCollector.cs b/src/Lucene.Net.Misc/Index/Sorter/EarlyTerminatingSortingCollector.cs
index 5eee50d7e4..ffaf538cdd 100644
--- a/src/Lucene.Net.Misc/Index/Sorter/EarlyTerminatingSortingCollector.cs
+++ b/src/Lucene.Net.Misc/Index/Sorter/EarlyTerminatingSortingCollector.cs
@@ -91,7 +91,7 @@ public EarlyTerminatingSortingCollector(ICollector @in, Sort sort, int numDocsTo
{
if (numDocsToCollect <= 0)
{
- throw new InvalidOperationException("numDocsToCollect must always be > 0, got " + m_segmentTotalCollect);
+ throw IllegalStateException.Create("numDocsToCollect must always be > 0, got " + m_segmentTotalCollect);
}
this.m_in = @in;
this.m_sort = sort;
diff --git a/src/Lucene.Net.Misc/Index/Sorter/Sorter.cs b/src/Lucene.Net.Misc/Index/Sorter/Sorter.cs
index ddc77a04dc..e0ffcf29d1 100644
--- a/src/Lucene.Net.Misc/Index/Sorter/Sorter.cs
+++ b/src/Lucene.Net.Misc/Index/Sorter/Sorter.cs
@@ -299,9 +299,9 @@ public override int Compare(int docID1, int docID2)
}
return docID1.CompareTo(docID2); // docid order tiebreak
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
}
@@ -332,25 +332,25 @@ public ScorerAnonymousClass()
public override float GetScore()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
- public override int Freq => throw new NotSupportedException();
+ public override int Freq => throw UnsupportedOperationException.Create();
- public override int DocID => throw new NotSupportedException();
+ public override int DocID => throw UnsupportedOperationException.Create();
public override int NextDoc()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override int Advance(int target)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override long GetCost()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
}
diff --git a/src/Lucene.Net.Misc/Index/Sorter/SortingMergePolicy.cs b/src/Lucene.Net.Misc/Index/Sorter/SortingMergePolicy.cs
index 65a40d0726..401cdca7d5 100644
--- a/src/Lucene.Net.Misc/Index/Sorter/SortingMergePolicy.cs
+++ b/src/Lucene.Net.Misc/Index/Sorter/SortingMergePolicy.cs
@@ -128,7 +128,7 @@ public override MergePolicy.DocMap GetDocMap(MergeState mergeState)
{
if (unsortedReaders == null)
{
- throw new InvalidOperationException();
+ throw IllegalStateException.Create();
}
if (docMap == null)
{
diff --git a/src/Lucene.Net.Misc/Misc/HighFreqTerms.cs b/src/Lucene.Net.Misc/Misc/HighFreqTerms.cs
index c91be30741..973a2e2d07 100644
--- a/src/Lucene.Net.Misc/Misc/HighFreqTerms.cs
+++ b/src/Lucene.Net.Misc/Misc/HighFreqTerms.cs
@@ -99,7 +99,7 @@ public static TermStats[] GetHighFreqTerms(IndexReader reader, int numTerms, str
Fields fields = MultiFields.GetFields(reader);
if (fields == null)
{
- throw new Exception("field " + field + " not found");
+ throw RuntimeException.Create("field " + field + " not found");
}
Terms terms = fields.GetTerms(field);
if (terms != null)
@@ -114,7 +114,7 @@ public static TermStats[] GetHighFreqTerms(IndexReader reader, int numTerms, str
Fields fields = MultiFields.GetFields(reader);
if (fields == null)
{
- throw new Exception("no fields found for this index");
+ throw RuntimeException.Create("no fields found for this index");
}
tiq = new TermStatsQueue(numTerms, comparer);
foreach (string fieldName in fields)
diff --git a/src/Lucene.Net.Queries/CommonTermsQuery.cs b/src/Lucene.Net.Queries/CommonTermsQuery.cs
index 01fd66643b..54156d79fe 100644
--- a/src/Lucene.Net.Queries/CommonTermsQuery.cs
+++ b/src/Lucene.Net.Queries/CommonTermsQuery.cs
@@ -143,9 +143,9 @@ public CommonTermsQuery(Occur highFreqOccur, Occur lowFreqOccur,
/// the term to add
public virtual void Add(Term term)
{
- if (term == null)
+ if (term is null)
{
- throw new ArgumentException("Term must not be null");
+ throw new ArgumentNullException(nameof(term), "Term must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.m_terms.Add(term);
}
diff --git a/src/Lucene.Net.Queries/CustomScoreQuery.cs b/src/Lucene.Net.Queries/CustomScoreQuery.cs
index 243b6f844b..3c865ca3cb 100644
--- a/src/Lucene.Net.Queries/CustomScoreQuery.cs
+++ b/src/Lucene.Net.Queries/CustomScoreQuery.cs
@@ -72,9 +72,9 @@ public CustomScoreQuery(Query subQuery, params FunctionQuery[] scoringQueries)
{
this.subQuery = subQuery;
this.scoringQueries = scoringQueries ?? Arrays.Empty();
- if (subQuery == null)
+ if (subQuery is null)
{
- throw new ArgumentException(" must not be null!");
+ throw new ArgumentNullException(nameof(subQuery), " must not be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
}
diff --git a/src/Lucene.Net.Queries/Function/DocValues/DocTermsIndexDocValues.cs b/src/Lucene.Net.Queries/Function/DocValues/DocTermsIndexDocValues.cs
index 8178834dbe..f209463bb7 100644
--- a/src/Lucene.Net.Queries/Function/DocValues/DocTermsIndexDocValues.cs
+++ b/src/Lucene.Net.Queries/Function/DocValues/DocTermsIndexDocValues.cs
@@ -45,7 +45,7 @@ protected DocTermsIndexDocValues(ValueSource vs, AtomicReaderContext context, st
{
m_termsIndex = FieldCache.DEFAULT.GetTermsIndex(context.AtomicReader, field);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsRuntimeException())
{
throw new DocTermsIndexException(field, e);
}
@@ -166,20 +166,20 @@ public override ValueFiller GetValueFiller()
#if FEATURE_SERIALIZABLE_EXCEPTIONS
[Serializable]
#endif
- public sealed class DocTermsIndexException : Exception
+ public sealed class DocTermsIndexException : Exception, IRuntimeException // LUCENENET specific: Added IRuntimeException for identification of the Java superclass in .NET
{
public DocTermsIndexException(string fieldName, Exception cause)
: base("Can't initialize DocTermsIndex to generate (function) FunctionValues for field: " + fieldName, cause)
{
- }
+ }
-#if FEATURE_SERIALIZABLE_EXCEPTIONS
- // For testing
- public DocTermsIndexException(string message)
+ // LUCENENET: For testing purposes
+ internal DocTermsIndexException(string message)
: base(message)
{
}
+#if FEATURE_SERIALIZABLE_EXCEPTIONS
///
/// Initializes a new instance of this class with serialized data.
///
diff --git a/src/Lucene.Net.Queries/Function/FunctionValues.cs b/src/Lucene.Net.Queries/Function/FunctionValues.cs
index 71aebbf6da..2b0fb4b333 100644
--- a/src/Lucene.Net.Queries/Function/FunctionValues.cs
+++ b/src/Lucene.Net.Queries/Function/FunctionValues.cs
@@ -40,7 +40,7 @@ public abstract class FunctionValues
{
public virtual byte ByteVal(int doc)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -48,7 +48,7 @@ public virtual byte ByteVal(int doc)
///
public virtual short Int16Val(int doc)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -56,7 +56,7 @@ public virtual short Int16Val(int doc)
///
public virtual float SingleVal(int doc)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -64,7 +64,7 @@ public virtual float SingleVal(int doc)
///
public virtual int Int32Val(int doc)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -72,18 +72,18 @@ public virtual int Int32Val(int doc)
///
public virtual long Int64Val(int doc)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public virtual double DoubleVal(int doc)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
// TODO: should we make a termVal, returns BytesRef?
public virtual string StrVal(int doc)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public virtual bool BoolVal(int doc)
@@ -125,11 +125,11 @@ public virtual bool Exists(int doc)
/// TODO: Maybe we can just use intVal for this...
public virtual int OrdVal(int doc)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
/// the number of unique sort ordinals this instance has
- public virtual int NumOrd => throw new NotSupportedException();
+ public virtual int NumOrd => throw UnsupportedOperationException.Create();
public abstract string ToString(int doc);
@@ -188,7 +188,7 @@ public virtual ValueFiller GetValueFiller()
//For Functions that can work with multiple values from the same document. This does not apply to all functions
public virtual void ByteVal(int doc, byte[] vals)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -196,7 +196,7 @@ public virtual void ByteVal(int doc, byte[] vals)
///
public virtual void Int16Val(int doc, short[] vals)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -204,7 +204,7 @@ public virtual void Int16Val(int doc, short[] vals)
///
public virtual void SingleVal(int doc, float[] vals)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -212,7 +212,7 @@ public virtual void SingleVal(int doc, float[] vals)
///
public virtual void Int32Val(int doc, int[] vals)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -220,18 +220,18 @@ public virtual void Int32Val(int doc, int[] vals)
///
public virtual void Int64Val(int doc, long[] vals)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public virtual void DoubleVal(int doc, double[] vals)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
// TODO: should we make a termVal, fills BytesRef[]?
public virtual void StrVal(int doc, string[] vals)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public virtual Explanation Explain(int doc)
diff --git a/src/Lucene.Net.Queries/Function/ValueSources/IDFValueSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/IDFValueSource.cs
index e64c3c3569..046c42260c 100644
--- a/src/Lucene.Net.Queries/Function/ValueSources/IDFValueSource.cs
+++ b/src/Lucene.Net.Queries/Function/ValueSources/IDFValueSource.cs
@@ -50,7 +50,7 @@ public override FunctionValues GetValues(IDictionary context, AtomicReaderContex
TFIDFSimilarity sim = AsTFIDF(searcher.Similarity, m_field);
if (sim == null)
{
- throw new NotSupportedException("requires a TFIDFSimilarity (such as DefaultSimilarity)");
+ throw UnsupportedOperationException.Create("requires a TFIDFSimilarity (such as DefaultSimilarity)");
}
int docfreq = searcher.IndexReader.DocFreq(new Term(m_indexedField, m_indexedBytes));
float idf = sim.Idf(docfreq, searcher.IndexReader.MaxDoc);
diff --git a/src/Lucene.Net.Queries/Function/ValueSources/JoinDocFreqValueSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/JoinDocFreqValueSource.cs
index 76b42e16ff..16f081c19c 100644
--- a/src/Lucene.Net.Queries/Function/ValueSources/JoinDocFreqValueSource.cs
+++ b/src/Lucene.Net.Queries/Function/ValueSources/JoinDocFreqValueSource.cs
@@ -93,9 +93,9 @@ public override int Int32Val(int doc)
return 0;
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception("caught exception in function " + outerInstance.GetDescription() + " : doc=" + doc, e);
+ throw RuntimeException.Create("caught exception in function " + outerInstance.GetDescription() + " : doc=" + doc, e);
}
}
}
diff --git a/src/Lucene.Net.Queries/Function/ValueSources/NormValueSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/NormValueSource.cs
index 6a270ab7d5..a9313b26ee 100644
--- a/src/Lucene.Net.Queries/Function/ValueSources/NormValueSource.cs
+++ b/src/Lucene.Net.Queries/Function/ValueSources/NormValueSource.cs
@@ -60,7 +60,7 @@ public override FunctionValues GetValues(IDictionary context, AtomicReaderContex
TFIDFSimilarity similarity = IDFValueSource.AsTFIDF(searcher.Similarity, m_field);
if (similarity == null)
{
- throw new NotSupportedException("requires a TFIDFSimilarity (such as DefaultSimilarity)");
+ throw UnsupportedOperationException.Create("requires a TFIDFSimilarity (such as DefaultSimilarity)");
}
NumericDocValues norms = readerContext.AtomicReader.GetNormValues(m_field);
diff --git a/src/Lucene.Net.Queries/Function/ValueSources/QueryValueSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/QueryValueSource.cs
index cb72e98b4a..2bde38d776 100644
--- a/src/Lucene.Net.Queries/Function/ValueSources/QueryValueSource.cs
+++ b/src/Lucene.Net.Queries/Function/ValueSources/QueryValueSource.cs
@@ -163,9 +163,9 @@ public override float SingleVal(int doc)
// a match!
return scorer.GetScore();
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception("caught exception in QueryDocVals(" + q + ") doc=" + doc, e);
+ throw RuntimeException.Create("caught exception in QueryDocVals(" + q + ") doc=" + doc, e);
}
}
@@ -204,9 +204,9 @@ public override bool Exists(int doc)
// a match!
return true;
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception("caught exception in QueryDocVals(" + q + ") doc=" + doc, e);
+ throw RuntimeException.Create("caught exception in QueryDocVals(" + q + ") doc=" + doc, e);
}
}
@@ -216,9 +216,9 @@ public override object ObjectVal(int doc)
{
return Exists(doc) ? scorer.GetScore() : (float?)null;
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception("caught exception in QueryDocVals(" + q + ") doc=" + doc, e);
+ throw RuntimeException.Create("caught exception in QueryDocVals(" + q + ") doc=" + doc, e);
}
}
@@ -268,9 +268,9 @@ public override ValueFiller GetValueFiller()
mutableValue.Value = scorer.GetScore();
mutableValue.Exists = true;
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception("caught exception in QueryDocVals(" + q + ") doc=" + doc, e);
+ throw RuntimeException.Create("caught exception in QueryDocVals(" + q + ") doc=" + doc, e);
}
});
}
diff --git a/src/Lucene.Net.Queries/Function/ValueSources/TFValueSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/TFValueSource.cs
index d1173d23fe..ce412bf865 100644
--- a/src/Lucene.Net.Queries/Function/ValueSources/TFValueSource.cs
+++ b/src/Lucene.Net.Queries/Function/ValueSources/TFValueSource.cs
@@ -52,7 +52,7 @@ public override FunctionValues GetValues(IDictionary context, AtomicReaderContex
var similarity = IDFValueSource.AsTFIDF(searcher.Similarity, m_indexedField);
if (similarity == null)
{
- throw new NotSupportedException("requires a TFIDFSimilarity (such as DefaultSimilarity)");
+ throw UnsupportedOperationException.Create("requires a TFIDFSimilarity (such as DefaultSimilarity)");
}
return new SingleDocValuesAnonymousClass(this, this, terms, similarity);
@@ -158,9 +158,9 @@ public override float SingleVal(int doc)
// a match!
return similarity.Tf(docs.Freq);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception("caught exception in function " + outerInstance.GetDescription() + " : doc=" + doc, e);
+ throw RuntimeException.Create("caught exception in function " + outerInstance.GetDescription() + " : doc=" + doc, e);
}
}
}
diff --git a/src/Lucene.Net.Queries/Function/ValueSources/TermFreqValueSource.cs b/src/Lucene.Net.Queries/Function/ValueSources/TermFreqValueSource.cs
index 39d217bc6c..c4e9b6fd6e 100644
--- a/src/Lucene.Net.Queries/Function/ValueSources/TermFreqValueSource.cs
+++ b/src/Lucene.Net.Queries/Function/ValueSources/TermFreqValueSource.cs
@@ -148,9 +148,9 @@ public override int Int32Val(int doc)
// a match!
return docs.Freq;
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception("caught exception in function " + outerInstance.GetDescription() + " : doc=" + doc, e);
+ throw RuntimeException.Create("caught exception in function " + outerInstance.GetDescription() + " : doc=" + doc, e);
}
}
}
diff --git a/src/Lucene.Net.Queries/Mlt/MoreLikeThis.cs b/src/Lucene.Net.Queries/Mlt/MoreLikeThis.cs
index fa089ae208..b1b5de1006 100644
--- a/src/Lucene.Net.Queries/Mlt/MoreLikeThis.cs
+++ b/src/Lucene.Net.Queries/Mlt/MoreLikeThis.cs
@@ -579,7 +579,8 @@ private void AddTermFrequencies(TextReader r, IDictionary termFre
{
if (Analyzer == null)
{
- throw new NotSupportedException("To use MoreLikeThis without " + "term vectors, you must provide an Analyzer");
+ throw UnsupportedOperationException.Create("To use MoreLikeThis without " +
+ "term vectors, you must provide an Analyzer");
}
var ts = Analyzer.GetTokenStream(fieldName, r);
try
diff --git a/src/Lucene.Net.Queries/TermFilter.cs b/src/Lucene.Net.Queries/TermFilter.cs
index f8f1c1e848..ce2d031741 100644
--- a/src/Lucene.Net.Queries/TermFilter.cs
+++ b/src/Lucene.Net.Queries/TermFilter.cs
@@ -33,13 +33,13 @@ public sealed class TermFilter : Filter
/// The term documents need to have in order to be a match for this filter.
public TermFilter(Term term)
{
- if (term == null)
+ if (term is null)
{
- throw new ArgumentException("Term must not be null");
+ throw new ArgumentNullException(nameof(term), "Term must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
- else if (term.Field == null)
+ else if (term.Field is null)
{
- throw new ArgumentException("Field must not be null");
+ throw new ArgumentNullException(nameof(term.Field), "term.Field must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
this.term = term;
}
diff --git a/src/Lucene.Net.Queries/TermsFilter.cs b/src/Lucene.Net.Queries/TermsFilter.cs
index c0f9c91b05..a9e23acc0c 100644
--- a/src/Lucene.Net.Queries/TermsFilter.cs
+++ b/src/Lucene.Net.Queries/TermsFilter.cs
@@ -64,6 +64,10 @@ private class FieldAndTermEnumAnonymousClass : FieldAndTermEnum
{
public FieldAndTermEnumAnonymousClass(IList terms)
{
+ // LUCENENET specific - added guard clause for null
+ if (terms is null)
+ throw new ArgumentNullException(nameof(terms));
+
if (terms.Count == 0)
{
throw new ArgumentException("no terms provided");
@@ -103,6 +107,10 @@ private class FieldAndTermEnumAnonymousClass2 : FieldAndTermEnum
public FieldAndTermEnumAnonymousClass2(string field, IList terms)
: base(field)
{
+ // LUCENENET specific - added guard clause for null
+ if (terms is null)
+ throw new ArgumentNullException(nameof(terms));
+
if (terms.Count == 0)
{
throw new ArgumentException("no terms provided");
diff --git a/src/Lucene.Net.QueryParser/Analyzing/AnalyzingQueryParser.cs b/src/Lucene.Net.QueryParser/Analyzing/AnalyzingQueryParser.cs
index 11849f6598..4857bc42cf 100644
--- a/src/Lucene.Net.QueryParser/Analyzing/AnalyzingQueryParser.cs
+++ b/src/Lucene.Net.QueryParser/Analyzing/AnalyzingQueryParser.cs
@@ -27,6 +27,12 @@ namespace Lucene.Net.QueryParsers.Analyzing
* limitations under the License.
*/
+ // LUCENENET: Special case exception - QueryParser has its own ParseException types that are generated.
+ // We won't know until we start generating QueryParser how to handle this scenario, but for now we are
+ // mapping this explicitly INSIDE of the namespace declaration to prevent our Lucene.ParseException from being
+ // used instead.
+ using ParseException = Lucene.Net.QueryParsers.Classic.ParseException;
+
///
/// Overrides Lucene's default so that Fuzzy-, Prefix-, Range-, and WildcardQuerys
/// are also passed through the given analyzer, but wildcard characters * and
@@ -206,7 +212,7 @@ protected internal virtual string AnalyzeSingleChunk(string field, string termSt
throw new ParseException(string.Format(@"Analyzer returned nothing for ""{0}""", chunk));
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
throw new ParseException(
string.Format(@"IO error while trying to analyze single term: ""{0}""", termStr), e);
diff --git a/src/Lucene.Net.QueryParser/Classic/FastCharStream.cs b/src/Lucene.Net.QueryParser/Classic/FastCharStream.cs
index 709a1602f3..e21c114d97 100644
--- a/src/Lucene.Net.QueryParser/Classic/FastCharStream.cs
+++ b/src/Lucene.Net.QueryParser/Classic/FastCharStream.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.IO;
using Console = Lucene.Net.Util.SystemConsole;
@@ -120,7 +120,7 @@ public void Done()
{
input.Dispose();
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
Console.Error.WriteLine("Caught: " + e + "; ignoring.");
}
diff --git a/src/Lucene.Net.QueryParser/Classic/MultiFieldQueryParser.cs b/src/Lucene.Net.QueryParser/Classic/MultiFieldQueryParser.cs
index 39447e262b..220d575806 100644
--- a/src/Lucene.Net.QueryParser/Classic/MultiFieldQueryParser.cs
+++ b/src/Lucene.Net.QueryParser/Classic/MultiFieldQueryParser.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Analysis;
+using Lucene.Net.Analysis;
using Lucene.Net.Search;
using Lucene.Net.Util;
using System;
@@ -270,8 +270,14 @@ protected internal override Query GetRegexpQuery(string field, string termStr)
///
public static Query Parse(LuceneVersion matchVersion, string[] queries, string[] fields, Analyzer analyzer)
{
+ // LUCENENET: Added null guard clauses
+ if (queries is null)
+ throw new ArgumentNullException(nameof(queries));
+ if (fields is null)
+ throw new ArgumentNullException(nameof(fields));
+
if (queries.Length != fields.Length)
- throw new ArgumentException("queries.length != fields.length");
+ throw new ArgumentException("queries.Length != fields.Length");
BooleanQuery bQuery = new BooleanQuery();
for (int i = 0; i < fields.Length; i++)
{
@@ -318,8 +324,16 @@ public static Query Parse(LuceneVersion matchVersion, string[] queries, string[]
///
public static Query Parse(LuceneVersion matchVersion, string query, string[] fields, Occur[] flags, Analyzer analyzer)
{
+ // LUCENENET: Added null guard clauses
+ if (query is null)
+ throw new ArgumentNullException(nameof(query));
+ if (fields is null)
+ throw new ArgumentNullException(nameof(fields));
+ if (flags is null)
+ throw new ArgumentNullException(nameof(flags));
+
if (fields.Length != flags.Length)
- throw new ArgumentException("fields.length != flags.length");
+ throw new ArgumentException("fields.Length != flags.Length");
BooleanQuery bQuery = new BooleanQuery();
for (int i = 0; i < fields.Length; i++)
{
@@ -364,6 +378,14 @@ public static Query Parse(LuceneVersion matchVersion, string query, string[] fie
/// if the length of the queries, fields, and flags array differ
public static Query Parse(LuceneVersion matchVersion, string[] queries, string[] fields, Occur[] flags, Analyzer analyzer)
{
+ // LUCENENET: Added null guard clauses
+ if (queries is null)
+ throw new ArgumentNullException(nameof(queries));
+ if (fields is null)
+ throw new ArgumentNullException(nameof(fields));
+ if (flags is null)
+ throw new ArgumentNullException(nameof(flags));
+
if (!(queries.Length == fields.Length && queries.Length == flags.Length))
throw new ArgumentException("queries, fields, and flags array have have different length");
BooleanQuery bQuery = new BooleanQuery();
diff --git a/src/Lucene.Net.QueryParser/Classic/QueryParser.cs b/src/Lucene.Net.QueryParser/Classic/QueryParser.cs
index 9c5993a6c4..a1794f88fb 100644
--- a/src/Lucene.Net.QueryParser/Classic/QueryParser.cs
+++ b/src/Lucene.Net.QueryParser/Classic/QueryParser.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Analysis;
+using Lucene.Net.Analysis;
using Lucene.Net.Search;
using Lucene.Net.Util;
using System;
@@ -157,7 +157,7 @@ public int Conjunction()
{
if (true) return ret;
}
- throw new InvalidOperationException("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public int Modifiers()
@@ -195,7 +195,7 @@ public int Modifiers()
{
if (true) return ret;
}
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
// This makes sure that there is no garbage after the query string
@@ -207,7 +207,7 @@ public override sealed Query TopLevelQuery(string field)
{
if (true) return q;
}
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public Query Query(string field)
@@ -259,7 +259,8 @@ public Query Query(string field)
if (true) return firstQuery;
}
- return GetBooleanQuery(clauses);
+ if (true) return GetBooleanQuery(clauses);
+ throw Error.Create("Missing return statement in function");
}
public Query Clause(string field)
@@ -327,7 +328,7 @@ public Query Clause(string field)
{
if (true) return HandleBoost(q, boost);
}
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public Query Term(string field)
@@ -538,7 +539,7 @@ public Query Term(string field)
throw new ParseException();
}
{ if (true) return HandleBoost(q, boost); }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
private bool Jj_2_1(int xla)
diff --git a/src/Lucene.Net.QueryParser/Classic/QueryParserBase.cs b/src/Lucene.Net.QueryParser/Classic/QueryParserBase.cs
index 962b492554..0d7b8f81d7 100644
--- a/src/Lucene.Net.QueryParser/Classic/QueryParserBase.cs
+++ b/src/Lucene.Net.QueryParser/Classic/QueryParserBase.cs
@@ -331,7 +331,7 @@ public virtual void SetDateResolution(string fieldName, DateTools.Resolution dat
{
if (string.IsNullOrEmpty(fieldName))
{
- throw new ArgumentNullException("fieldName cannot be null or empty string.");
+ throw new ArgumentNullException(nameof(fieldName), "fieldName cannot be null or empty string."); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (fieldToDateResolution == null)
@@ -352,7 +352,7 @@ public virtual DateTools.Resolution GetDateResolution(string fieldName)
{
if (string.IsNullOrEmpty(fieldName))
{
- throw new ArgumentNullException("fieldName cannot be null or empty string.");
+ throw new ArgumentNullException(nameof(fieldName), "fieldName cannot be null or empty string."); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (fieldToDateResolution == null)
@@ -435,7 +435,7 @@ protected internal virtual void AddClause(IList clauses, int conj
else if (!required && prohibited)
clauses.Add(NewBooleanClause(q, Occur.MUST_NOT));
else
- throw new Exception("Clause cannot be both required and prohibited");
+ throw RuntimeException.Create("Clause cannot be both required and prohibited");
}
/// throw in overridden method to disallow
@@ -614,9 +614,9 @@ protected internal virtual BytesRef AnalyzeMultitermTerm(string field, string pa
source.End();
return BytesRef.DeepCopyOf(bytes);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception("Error analyzing multiTerm term: " + part, e);
+ throw RuntimeException.Create("Error analyzing multiTerm term: " + part, e);
}
finally
{
@@ -885,7 +885,7 @@ internal virtual Query HandleBareFuzzy(string qfield, Token fuzzySlop, string te
// Perhaps just make it a non-default option?
fms = float.Parse(fuzzySlop.Image.Substring(1), CultureInfo.InvariantCulture);
}
- catch (Exception /*ignored*/) { }
+ catch (Exception ignored) when (ignored.IsException()) { }
if (fms < 0.0f)
{
throw new ParseException("Minimum similarity for a FuzzyQuery has to be between 0.0f and 1.0f !");
@@ -916,7 +916,7 @@ internal virtual Query HandleQuotedTerm(string qfield, Token term, Token fuzzySl
// Perhaps just make it a non-default option?
s = (int)float.Parse(fuzzySlop.Image.Substring(1), CultureInfo.InvariantCulture);
}
- catch (Exception /*ignored*/) { }
+ catch (Exception ignored) when (ignored.IsException()) { }
}
return GetFieldQuery(qfield, DiscardEscapeChar(term.Image.Substring(1, term.Image.Length - 2)), s);
}
@@ -939,7 +939,7 @@ internal virtual Query HandleBoost(Query q, Token boost)
// Perhaps just make it a non-default option?
f = float.Parse(boost.Image, CultureInfo.InvariantCulture);
}
- catch (Exception /*ignored*/)
+ catch (Exception ignored) when (ignored.IsException())
{
/* Should this be handled somehow? (defaults to "no boost", if
* boost number is invalid)
@@ -1069,6 +1069,10 @@ private static int HexToInt32(char c)
///
public static string Escape(string s)
{
+ // LUCENENET specific: Added guard clause for null
+ if (s is null)
+ throw new ArgumentNullException(nameof(s));
+
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
diff --git a/src/Lucene.Net.QueryParser/Classic/QueryParserTokenManager.cs b/src/Lucene.Net.QueryParser/Classic/QueryParserTokenManager.cs
index f307bb7d91..a1b87821b8 100644
--- a/src/Lucene.Net.QueryParser/Classic/QueryParserTokenManager.cs
+++ b/src/Lucene.Net.QueryParser/Classic/QueryParserTokenManager.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Support.IO;
+using Lucene.Net.Support.IO;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
@@ -111,7 +111,7 @@ private int JjStartNfaWithStates_2(int pos, int kind, int state)
{
m_curChar = m_input_stream.ReadChar();
}
- catch (IOException)
+ catch (Exception e) when (e.IsIOException())
{
return pos + 1;
}
@@ -728,7 +728,7 @@ private int JjMoveNfa_2(int startState, int curPos)
{
m_curChar = m_input_stream.ReadChar();
}
- catch (IOException)
+ catch (Exception e) when (e.IsIOException())
{
return curPos;
}
@@ -829,7 +829,7 @@ private int JjMoveNfa_0(int startState, int curPos)
{
m_curChar = m_input_stream.ReadChar();
}
- catch (IOException)
+ catch (Exception e) when (e.IsIOException())
{
return curPos;
}
@@ -882,7 +882,7 @@ private int JjMoveStringLiteralDfa1_1(long active0)
{
m_curChar = m_input_stream.ReadChar();
}
- catch (IOException)
+ catch (Exception e) when (e.IsIOException())
{
JjStopStringLiteralDfa_1(0, active0);
return 1;
@@ -909,7 +909,7 @@ private int JjStartNfaWithStates_1(int pos, int kind, int state)
{
m_curChar = m_input_stream.ReadChar();
}
- catch (IOException)
+ catch (Exception e) when (e.IsIOException())
{
return pos + 1;
}
@@ -1074,7 +1074,7 @@ private int JjMoveNfa_1(int startState, int curPos)
{
m_curChar = m_input_stream.ReadChar();
}
- catch (IOException)
+ catch (Exception e) when (e.IsIOException())
{
return curPos;
}
@@ -1252,7 +1252,7 @@ public virtual Token GetNextToken()
{
m_curChar = m_input_stream.BeginToken();
}
- catch (IOException)
+ catch (Exception e) when (e.IsIOException())
{
jjmatchedKind = 0;
matchedToken = JjFillToken();
@@ -1306,7 +1306,7 @@ public virtual Token GetNextToken()
{
m_input_stream.ReadChar(); m_input_stream.BackUp(1);
}
- catch (IOException)
+ catch (Exception e) when (e.IsIOException())
{
EOFSeen = true;
error_after = curPos <= 1?"":m_input_stream.Image;
diff --git a/src/Lucene.Net.QueryParser/Classic/TokenMgrError.cs b/src/Lucene.Net.QueryParser/Classic/TokenMgrError.cs
index 261a3c8b4e..48fdfd2c03 100644
--- a/src/Lucene.Net.QueryParser/Classic/TokenMgrError.cs
+++ b/src/Lucene.Net.QueryParser/Classic/TokenMgrError.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
#if FEATURE_SERIALIZABLE_EXCEPTIONS
using System.Runtime.Serialization;
using System.Security.Permissions;
@@ -30,7 +30,7 @@ namespace Lucene.Net.QueryParsers.Classic
#if FEATURE_SERIALIZABLE_EXCEPTIONS
[Serializable]
#endif
- public class TokenMgrError : Exception
+ public class TokenMgrError : Exception, IError // LUCENENET specific: Added IError for identification of the Java superclass in .NET
{
/*
* Ordinals for various reasons why an Error of this type can be thrown.
diff --git a/src/Lucene.Net.QueryParser/ComplexPhrase/ComplexPhraseQueryParser.cs b/src/Lucene.Net.QueryParser/ComplexPhrase/ComplexPhraseQueryParser.cs
index e5c5e9c116..6ec52523da 100644
--- a/src/Lucene.Net.QueryParser/ComplexPhrase/ComplexPhraseQueryParser.cs
+++ b/src/Lucene.Net.QueryParser/ComplexPhrase/ComplexPhraseQueryParser.cs
@@ -26,6 +26,12 @@ namespace Lucene.Net.QueryParsers.ComplexPhrase
* limitations under the License.
*/
+ // LUCENENET: Special case exception - QueryParser has its own ParseException types that are generated.
+ // We won't know until we start generating QueryParser how to handle this scenario, but for now we are
+ // mapping this explicitly INSIDE of the namespace declaration to prevent our Lucene.ParseException from being
+ // used instead.
+ using ParseException = Lucene.Net.QueryParsers.Classic.ParseException;
+
///
/// which permits complex phrase query syntax eg "(john jon
/// jonathan~) peters*".
@@ -142,7 +148,7 @@ protected override Query NewTermQuery(Term term)
}
catch (ParseException pe)
{
- throw new Exception("Error parsing complex phrase", pe);
+ throw RuntimeException.Create("Error parsing complex phrase", pe);
}
}
return base.NewTermQuery(term);
diff --git a/src/Lucene.Net.QueryParser/Flexible/Core/Config/AbstractQueryConfig.cs b/src/Lucene.Net.QueryParser/Flexible/Core/Config/AbstractQueryConfig.cs
index eb44707bd1..f0ab7c72bd 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Core/Config/AbstractQueryConfig.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Core/Config/AbstractQueryConfig.cs
@@ -46,9 +46,9 @@ internal AbstractQueryConfig()
/// the value held by the given key
public virtual T Get(ConfigurationKey key)
{
- if (key == null)
+ if (key is null)
{
- throw new ArgumentException("key cannot be null!");
+ throw new ArgumentNullException(nameof(key), "key cannot be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
this.configMap.TryGetValue(key, out object result);
return result == null ? default : (T)result;
@@ -62,9 +62,9 @@ public virtual T Get(ConfigurationKey key)
/// true if there is a value set with the given key, otherwise false
public virtual bool Has(ConfigurationKey key)
{
- if (key == null)
+ if (key is null)
{
- throw new ArgumentException("key cannot be null!");
+ throw new ArgumentNullException(nameof(key), "key cannot be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
return this.configMap.ContainsKey(key);
@@ -78,9 +78,9 @@ public virtual bool Has(ConfigurationKey key)
/// value to set
public virtual void Set(ConfigurationKey key, T value)
{
- if (key == null)
+ if (key is null)
{
- throw new ArgumentException("key cannot be null!");
+ throw new ArgumentNullException(nameof(key), "key cannot be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (value == null)
@@ -101,9 +101,9 @@ public virtual void Set(ConfigurationKey key, T value)
/// true if the key and value was set and removed, otherwise false
public virtual bool Unset(ConfigurationKey key)
{
- if (key == null)
+ if (key is null)
{
- throw new ArgumentException("key cannot be null!");
+ throw new ArgumentNullException(nameof(key), "key cannot be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
return this.configMap.Remove(key);
diff --git a/src/Lucene.Net.QueryParser/Flexible/Core/Config/FieldConfig.cs b/src/Lucene.Net.QueryParser/Flexible/Core/Config/FieldConfig.cs
index 25fef283eb..bec2600e2e 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Core/Config/FieldConfig.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Core/Config/FieldConfig.cs
@@ -33,7 +33,7 @@ public class FieldConfig : AbstractQueryConfig
/// if the field name is null
public FieldConfig(string fieldName)
{
- this.fieldName = fieldName ?? throw new ArgumentNullException(nameof(fieldName), "field name should not be null!");
+ this.fieldName = fieldName ?? throw new ArgumentNullException(nameof(fieldName), "field name should not be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
///
diff --git a/src/Lucene.Net.QueryParser/Flexible/Core/Nodes/PathQueryNode.cs b/src/Lucene.Net.QueryParser/Flexible/Core/Nodes/PathQueryNode.cs
index 335ef2bd6e..efc47f84f4 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Core/Nodes/PathQueryNode.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Core/Nodes/PathQueryNode.cs
@@ -115,7 +115,7 @@ public PathQueryNode(IList pathElements)
if (pathElements.Count <= 1)
{
// this should not happen
- throw new Exception(
+ throw RuntimeException.Create(
"PathQuerynode requires more 2 or more path elements.");
}
}
diff --git a/src/Lucene.Net.QueryParser/Flexible/Core/Processors/QueryNodeProcessorImpl.cs b/src/Lucene.Net.QueryParser/Flexible/Core/Processors/QueryNodeProcessorImpl.cs
index 1ab9d378e6..c7483f04ec 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Core/Processors/QueryNodeProcessorImpl.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Core/Processors/QueryNodeProcessorImpl.cs
@@ -119,8 +119,8 @@ protected virtual void ProcessChildren(IQueryNode queryTree)
if (child2 == null)
{
- throw new NullReferenceException(); // LUCENENET TODO: Change to ArgumentException ?
-
+ // LUCENENET: Changed from NullPointerException to InvalidOperationException (which isn't caught anywhere outside of tests)
+ throw IllegalStateException.Create($"{this.GetType().Name}.PostProcessNode() must not return 'null'.");
}
newChildren.Add(child2);
diff --git a/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeError.cs b/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeError.cs
index bee10892e6..329d306413 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeError.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeError.cs
@@ -34,7 +34,7 @@ namespace Lucene.Net.QueryParsers.Flexible.Core
#if FEATURE_SERIALIZABLE_EXCEPTIONS
[Serializable]
#endif
- public class QueryNodeError : Exception, INLSException
+ public class QueryNodeError : Exception, INLSException, IError // LUCENENET specific: Added IError for identification of the Java superclass in .NET
{
private readonly IMessage message; // LUCENENET: marked readonly
@@ -69,12 +69,12 @@ public QueryNodeError(IMessage message, Exception throwable)
this.message = message;
}
-#if FEATURE_SERIALIZABLE_EXCEPTIONS
- // For testing
- public QueryNodeError(string message)
+ // LUCENENET: For testing purposes
+ internal QueryNodeError(string message)
: base(message)
{ }
+#if FEATURE_SERIALIZABLE_EXCEPTIONS
///
/// Initializes a new instance of this class with serialized data.
///
diff --git a/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeException.cs b/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeException.cs
index 22dfb63fe2..29b908009a 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeException.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeException.cs
@@ -63,12 +63,12 @@ public QueryNodeException(IMessage message, Exception throwable)
this.m_message = message;
}
-#if FEATURE_SERIALIZABLE_EXCEPTIONS
- // For testing
- public QueryNodeException(string message)
+ // LUCENENET: For testing purposes
+ internal QueryNodeException(string message)
: base(message)
{ }
+#if FEATURE_SERIALIZABLE_EXCEPTIONS
///
/// Initializes a new instance of this class with serialized data.
///
diff --git a/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeParseException.cs b/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeParseException.cs
index b2c6203707..8b9f615fc4 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeParseException.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Core/QueryNodeParseException.cs
@@ -62,12 +62,12 @@ public QueryNodeParseException(IMessage message, Exception throwable)
{
}
-#if FEATURE_SERIALIZABLE_EXCEPTIONS
- // For testing
- public QueryNodeParseException(string message)
+ // LUCENENET: For testing purposes
+ internal QueryNodeParseException(string message)
: base(message)
{ }
+#if FEATURE_SERIALIZABLE_EXCEPTIONS
///
/// Initializes a new instance of this class with serialized data.
///
diff --git a/src/Lucene.Net.QueryParser/Flexible/Core/QueryParserHelper.cs b/src/Lucene.Net.QueryParser/Flexible/Core/QueryParserHelper.cs
index de50d0a0fe..cf1a3bbb4b 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Core/QueryParserHelper.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Core/QueryParserHelper.cs
@@ -107,7 +107,7 @@ public virtual void SetQueryNodeProcessor(IQueryNodeProcessor processor)
///
public virtual void SetSyntaxParser(ISyntaxParser syntaxParser)
{
- this.syntaxParser = syntaxParser ?? throw new ArgumentNullException(nameof(syntaxParser), "textParser should not be null!");
+ this.syntaxParser = syntaxParser ?? throw new ArgumentNullException(nameof(syntaxParser), "textParser should not be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
///
@@ -119,7 +119,7 @@ public virtual void SetSyntaxParser(ISyntaxParser syntaxParser)
///
public virtual void SetQueryBuilder(IQueryBuilder queryBuilder)
{
- this.builder = queryBuilder ?? throw new ArgumentNullException(nameof(queryBuilder), "queryBuilder should not be null!");
+ this.builder = queryBuilder ?? throw new ArgumentNullException(nameof(queryBuilder), "queryBuilder should not be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
///
diff --git a/src/Lucene.Net.QueryParser/Flexible/Messages/NLS.cs b/src/Lucene.Net.QueryParser/Flexible/Messages/NLS.cs
index bdaf3adbef..2bd901bc96 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Messages/NLS.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Messages/NLS.cs
@@ -124,7 +124,7 @@ protected static void InitializeMessages(string bundleName, Type clazz)
if (!bundles.ContainsKey(bundleName))
bundles[bundleName] = clazz;
}
- catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsThrowable())
{
// ignore all errors and exceptions
// because this function is supposed to be called at class load time.
@@ -147,9 +147,7 @@ private static string GetResourceBundleObject(string messageKey, CultureInfo loc
if (obj != null)
return obj;
}
-#pragma warning disable 168
- catch (MissingManifestResourceException e)
-#pragma warning restore 168
+ catch (Exception e) when (e.IsMissingResourceException())
{
// just continue it might be on the next resource bundle
}
@@ -209,12 +207,12 @@ private static void ValidateMessage(string key, Type clazz)
}
}
}
- catch (MissingManifestResourceException) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsMissingResourceException())
{
//System.err.println("WARN: Message with key:" + key + " and locale: "
// + Locale.getDefault() + " not found.");
}
- catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsThrowable())
{
// ignore all other errors and exceptions
// since this code is just a test to see if the message is present on the
diff --git a/src/Lucene.Net.QueryParser/Flexible/Precedence/Processors/BooleanModifiersQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Precedence/Processors/BooleanModifiersQueryNodeProcessor.cs
index 17e347eda6..87b9e4b65b 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Precedence/Processors/BooleanModifiersQueryNodeProcessor.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Precedence/Processors/BooleanModifiersQueryNodeProcessor.cs
@@ -50,7 +50,7 @@ public override IQueryNode Process(IQueryNode queryTree)
{
Operator? op = GetQueryConfigHandler().Get(ConfigurationKeys.DEFAULT_OPERATOR);
- if (op == null)
+ if (op is null)
{
throw new ArgumentException(
"StandardQueryConfigHandler.ConfigurationKeys.DEFAULT_OPERATOR should be set on the QueryConfigHandler");
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/NumericConfig.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/NumericConfig.cs
index 67d842c912..a59a2134a7 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/NumericConfig.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/NumericConfig.cs
@@ -67,7 +67,7 @@ public virtual int PrecisionStep
public virtual NumberFormat NumberFormat
{
get => format;
- set => format = value ?? throw new ArgumentException("format cannot be null!");
+ set => format = value ?? throw new ArgumentNullException(nameof(NumberFormat), "format cannot be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
///
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/NumericFieldConfigListener.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/NumericFieldConfigListener.cs
index 911e711820..4e7323e4ba 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Config/NumericFieldConfigListener.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Config/NumericFieldConfigListener.cs
@@ -41,7 +41,7 @@ public class NumericFieldConfigListener : IFieldConfigListener
/// the it will listen too
public NumericFieldConfigListener(QueryConfigHandler config)
{
- this.config = config ?? throw new ArgumentNullException(nameof(config), "config cannot be null!");
+ this.config = config ?? throw new ArgumentNullException(nameof(config), "config cannot be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
public virtual void BuildFieldConfig(FieldConfig fieldConfig)
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Nodes/NumericRangeQueryNode.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Nodes/NumericRangeQueryNode.cs
index a3899816d5..34e4d3324b 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Nodes/NumericRangeQueryNode.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Nodes/NumericRangeQueryNode.cs
@@ -90,10 +90,9 @@ private static NumericType GetNumericDataType(/*Number*/ object number)
public virtual void SetBounds(NumericQueryNode lower, NumericQueryNode upper,
bool lowerInclusive, bool upperInclusive, NumericConfig numericConfig)
{
-
- if (numericConfig == null)
+ if (numericConfig is null)
{
- throw new ArgumentException("numericConfig cannot be null!");
+ throw new ArgumentNullException(nameof(numericConfig), "numericConfig cannot be null!"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
NumericType lowerNumberType, upperNumberType;
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/EscapeQuerySyntaxImpl.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/EscapeQuerySyntaxImpl.cs
index 544abe13f9..315e32b91c 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/EscapeQuerySyntaxImpl.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/EscapeQuerySyntaxImpl.cs
@@ -116,11 +116,19 @@ private static ICharSequence EscapeTerm(ICharSequence term, CultureInfo locale)
/// the new character to prefix sequence1 in return string.
///
/// the new
+ /// , , or is null.
private static ICharSequence ReplaceIgnoreCase(ICharSequence @string,
string sequence1, string escapeChar, CultureInfo locale)
{
- if (escapeChar == null || sequence1 == null || @string == null)
- throw new NullReferenceException(); // LUCNENET TODO: ArgumentException...
+ // LUCENENET specific - changed from NullPointerException to ArgumentNullException (.NET convention)
+ if (escapeChar is null)
+ throw new ArgumentNullException(nameof(escapeChar));
+ if (sequence1 is null)
+ throw new ArgumentNullException(nameof(sequence1));
+ if (@string is null)
+ throw new ArgumentNullException(nameof(@string));
+ if (locale is null)
+ throw new ArgumentNullException(nameof(locale));
// empty string case
int count = @string.Length;
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/FastCharStream.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/FastCharStream.cs
index 46da7ecea4..85fef748da 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/FastCharStream.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/FastCharStream.cs
@@ -1,4 +1,5 @@
-using System.IO;
+using System;
+using System.IO;
namespace Lucene.Net.QueryParsers.Flexible.Standard.Parser
{
@@ -118,7 +119,7 @@ public void Done()
{
input.Dispose();
}
- catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsIOException())
{
// ignore
}
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/StandardSyntaxParser.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/StandardSyntaxParser.cs
index f060ca52c6..43af963b1a 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/StandardSyntaxParser.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/StandardSyntaxParser.cs
@@ -67,12 +67,12 @@ public IQueryNode Parse(string query, string field)
IQueryNode querynode = TopLevelQuery(field);
return querynode;
}
- catch (ParseException tme)
+ catch (Lucene.Net.QueryParsers.Flexible.Standard.Parser.ParseException tme) // LUCENENET: Flexible QueryParser has its own ParseException that is different than the one in Support
{
tme.SetQuery(query);
- throw tme;
+ throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
- catch (Exception tme)
+ catch (Exception tme) when (tme.IsError())
{
IMessage message = new Message(QueryParserMessages.INVALID_SYNTAX_CANNOT_PARSE, query, tme.Message);
QueryNodeParseException e = new QueryNodeParseException(tme);
@@ -112,7 +112,7 @@ public int Conjunction()
break;
}
{ if (true) return ret; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public Modifier Modifiers()
@@ -148,7 +148,7 @@ public Modifier Modifiers()
break;
}
{ if (true) return ret; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
// This makes sure that there is no garbage after the query string
@@ -158,7 +158,7 @@ public IQueryNode TopLevelQuery(string field)
q = Query(field);
Jj_consume_token(0);
{ if (true) return q; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
@@ -215,7 +215,7 @@ public IQueryNode Query(string field)
{
{ if (true) return first; }
}
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public IQueryNode DisjQuery(string field)
@@ -253,7 +253,7 @@ public IQueryNode DisjQuery(string field)
{
{ if (true) return first; }
}
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public IQueryNode ConjQuery(string field)
@@ -291,7 +291,7 @@ public IQueryNode ConjQuery(string field)
{
{ if (true) return first; }
}
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
// QueryNode Query(CharSequence field) :
@@ -343,7 +343,7 @@ public IQueryNode ModClause(string field)
q = new ModifierQueryNode(q, mods);
}
{ if (true) return q; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public IQueryNode Clause(string field)
@@ -461,7 +461,7 @@ public IQueryNode Clause(string field)
"*", term.BeginColumn, term.EndColumn);
break;
default:
- { if (true) throw new Exception("Unhandled case: operator=" + @operator.ToString()); }
+ { if (true) throw Error.Create("Unhandled case: operator=" + @operator.ToString()); }
}
q = new TermRangeQueryNode(qLower, qUpper, lowerInclusive, upperInclusive);
break;
@@ -544,19 +544,18 @@ public IQueryNode Clause(string field)
}
if (boost != null)
{
- float f = (float)1.0;
+ // LUCENENET specific - parse without throwing exceptions
+ float f = float.TryParse(boost.Image, NumberStyles.Float, CultureInfo.InvariantCulture, out float temp) ? temp : 1.0f;
try
{
- f = Convert.ToSingle(boost.Image, CultureInfo.InvariantCulture);
// avoid boosting null queries, such as those caused by stop words
if (q != null)
{
q = new BoostQueryNode(q, f);
}
}
- catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception ignored) when (ignored.IsException())
{
- //ignored
/* Should this be handled somehow? (defaults to "no boost", if
* boost number is invalid)
*/
@@ -564,7 +563,7 @@ public IQueryNode Clause(string field)
}
if (group) { q = new GroupQueryNode(q); }
{ if (true) return q; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public IQueryNode Term(string field)
@@ -634,14 +633,8 @@ public IQueryNode Term(string field)
}
if (fuzzy)
{
- float fms = defaultMinSimilarity;
- try
- {
- fms = Convert.ToSingle(fuzzySlop.Image.Substring(1), CultureInfo.InvariantCulture);
- }
-#pragma warning disable 168
- catch (Exception ignored) { }
-#pragma warning restore 168
+ // LUCENENET specific: parse without throwing exceptions
+ float fms = float.TryParse(fuzzySlop.Image.Substring(1), NumberStyles.Float, CultureInfo.InvariantCulture, out float temp) ? temp : defaultMinSimilarity;
if (fms < 0.0f)
{
{ if (true) throw new ParseException(new Message(QueryParserMessages.INVALID_SYNTAX_FUZZY_LIMITS)); }
@@ -774,17 +767,20 @@ public IQueryNode Term(string field)
if (fuzzySlop != null)
{
- try
- {
- phraseSlop = (int)Convert.ToSingle(fuzzySlop.Image.Substring(1), CultureInfo.InvariantCulture);
- q = new SlopQueryNode(q, phraseSlop);
- }
- catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ // LUCENENET: don't let parsing throw exceptions
+ if (float.TryParse(fuzzySlop.Image.Substring(1), NumberStyles.Float, CultureInfo.InvariantCulture, out float temp))
{
- // ignored
- /* Should this be handled somehow? (defaults to "no PhraseSlop", if
- * slop number is invalid)
- */
+ try
+ {
+ phraseSlop = (int)temp;
+ q = new SlopQueryNode(q, phraseSlop);
+ }
+ catch (Exception ignored) when (ignored.IsException())
+ {
+ /* Should this be handled somehow? (defaults to "no PhraseSlop", if
+ * slop number is invalid)
+ */
+ }
}
}
break;
@@ -795,26 +791,25 @@ public IQueryNode Term(string field)
}
if (boost != null)
{
- float f = (float)1.0;
+ // LUCENENET specific: parse without throwing exceptions
+ float f = float.TryParse(boost.Image, NumberStyles.Float, CultureInfo.InvariantCulture, out float temp) ? temp : 1.0f;
try
{
- f = Convert.ToSingle(boost.Image, CultureInfo.InvariantCulture);
// avoid boosting null queries, such as those caused by stop words
if (q != null)
{
q = new BoostQueryNode(q, f);
}
}
- catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception ignored) when (ignored.IsException())
{
- // ignored
/* Should this be handled somehow? (defaults to "no boost", if
* boost number is invalid)
*/
}
}
{ if (true) return q; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
private bool Jj_2_1(int xla)
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/StandardSyntaxParserTokenManager.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/StandardSyntaxParserTokenManager.cs
index 1b73994a95..57646672fc 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/StandardSyntaxParserTokenManager.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/StandardSyntaxParserTokenManager.cs
@@ -1,5 +1,6 @@
using Lucene.Net.Support.IO;
using System.Diagnostics.CodeAnalysis;
+using System;
using System.IO;
using Console = Lucene.Net.Util.SystemConsole;
@@ -88,9 +89,7 @@ private int JjMoveStringLiteralDfa0_2()
private int JjMoveStringLiteralDfa1_2(long active0)
{
try { m_curChar = m_input_stream.ReadChar(); }
-#pragma warning disable 168
- catch (IOException e)
-#pragma warning restore 168
+ catch (Exception e) when (e.IsIOException())
{
JjStopStringLiteralDfa_2(0, active0);
return 1;
@@ -429,9 +428,7 @@ private int JjMoveNfa_2(int startState, int curPos)
if ((i = jjnewStateCnt) == (startsAt = 33 - (jjnewStateCnt = startsAt)))
return curPos;
try { m_curChar = m_input_stream.ReadChar(); }
-#pragma warning disable 168
- catch (IOException e) { return curPos; }
-#pragma warning restore 168
+ catch (Exception e) when (e.IsIOException()) { return curPos; }
}
}
private int JjMoveStringLiteralDfa0_0()
@@ -517,9 +514,7 @@ private int JjMoveNfa_0(int startState, int curPos)
if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
return curPos;
try { m_curChar = m_input_stream.ReadChar(); }
-#pragma warning disable 168
- catch (IOException e) { return curPos; }
-#pragma warning restore 168
+ catch (Exception e) when (e.IsIOException()) { return curPos; }
}
}
private int JjStopStringLiteralDfa_1(int pos, long active0)
@@ -558,9 +553,7 @@ private int JjMoveStringLiteralDfa0_1()
private int JjMoveStringLiteralDfa1_1(long active0)
{
try { m_curChar = m_input_stream.ReadChar(); }
-#pragma warning disable 168
- catch (IOException e)
-#pragma warning restore 168
+ catch (Exception e) when (e.IsIOException())
{
JjStopStringLiteralDfa_1(0, active0);
return 1;
@@ -581,9 +574,7 @@ private int JjStartNfaWithStates_1(int pos, int kind, int state)
jjmatchedKind = kind;
jjmatchedPos = pos;
try { m_curChar = m_input_stream.ReadChar(); }
-#pragma warning disable 168
- catch (IOException e) { return pos + 1; }
-#pragma warning restore 168
+ catch (Exception e) when (e.IsIOException()) { return pos + 1; }
return JjMoveNfa_1(state, pos + 1);
}
private int JjMoveNfa_1(int startState, int curPos)
@@ -724,9 +715,7 @@ private int JjMoveNfa_1(int startState, int curPos)
if ((i = jjnewStateCnt) == (startsAt = 7 - (jjnewStateCnt = startsAt)))
return curPos;
try { m_curChar = m_input_stream.ReadChar(); }
-#pragma warning disable 168
- catch (IOException e) { return curPos; }
-#pragma warning restore 168
+ catch (Exception e) when (e.IsIOException()) { return curPos; }
}
}
internal static readonly int[] jjnextStates = {
@@ -887,9 +876,7 @@ public virtual Token GetNextToken()
{
m_curChar = m_input_stream.BeginToken();
}
-#pragma warning disable 168
- catch (IOException e)
-#pragma warning restore 168
+ catch (Exception e) when (e.IsIOException())
{
jjmatchedKind = 0;
matchedToken = JjFillToken();
@@ -937,9 +924,7 @@ public virtual Token GetNextToken()
string error_after = null;
bool EOFSeen = false;
try { m_input_stream.ReadChar(); m_input_stream.BackUp(1); }
-#pragma warning disable 168
- catch (IOException e1)
-#pragma warning restore 168
+ catch (Exception e1) when (e1.IsIOException())
{
EOFSeen = true;
error_after = curPos <= 1 ? "" : m_input_stream.GetImage();
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/TokenMgrError.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/TokenMgrError.cs
index c5678c5fe9..85bae807d5 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/TokenMgrError.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Parser/TokenMgrError.cs
@@ -33,7 +33,7 @@ namespace Lucene.Net.QueryParsers.Flexible.Standard.Parser
#if FEATURE_SERIALIZABLE_EXCEPTIONS
[Serializable]
#endif
- public class TokenMgrError : Exception
+ public class TokenMgrError : Exception, IError // LUCENENET specific: Added IError for identification of the Java superclass in .NET
{
// Ordinals for various reasons why an Error of this type can be thrown.
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/AnalyzerQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/AnalyzerQueryNodeProcessor.cs
index 2579e3e1be..9494ac5c95 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/AnalyzerQueryNodeProcessor.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/AnalyzerQueryNodeProcessor.cs
@@ -144,16 +144,14 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
}
}
}
-#pragma warning disable 168
- catch (IOException e)
-#pragma warning restore 168
+ catch (Exception e) when (e.IsIOException())
{
// ignore
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
finally
{
@@ -185,7 +183,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
if (Debugging.AssertsEnabled) Debugging.Assert(hasNext == true);
term = termAtt.ToString();
}
- catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsIOException())
{
// safe to ignore, because we know the number of tokens
}
@@ -214,7 +212,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
if (Debugging.AssertsEnabled) Debugging.Assert(hasNext == true);
term = termAtt.ToString();
}
- catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsIOException())
{
// safe to ignore, because we know the number of tokens
}
@@ -239,7 +237,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
if (Debugging.AssertsEnabled) Debugging.Assert(hasNext == true);
term = termAtt.ToString();
}
- catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsIOException())
{
// safe to ignore, because we know the number of tokens
}
@@ -308,7 +306,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
positionIncrement = posIncrAtt.PositionIncrement;
}
}
- catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsIOException())
{
// safe to ignore, because we know the number of tokens
}
@@ -379,7 +377,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
positionIncrement = posIncrAtt.PositionIncrement;
}
}
- catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsIOException())
{
// safe to ignore, because we know the number of tokens
}
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/BooleanQuery2ModifierNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/BooleanQuery2ModifierNodeProcessor.cs
index 67a2d33fef..43d85a30f1 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/BooleanQuery2ModifierNodeProcessor.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/BooleanQuery2ModifierNodeProcessor.cs
@@ -69,7 +69,7 @@ public virtual IQueryNode Process(IQueryNode queryTree)
Operator? op = GetQueryConfigHandler().Get(
ConfigurationKeys.DEFAULT_OPERATOR);
- if (op == null)
+ if (op is null)
{
throw new ArgumentException(
"StandardQueryConfigHandler.ConfigurationKeys.DEFAULT_OPERATOR should be set on the QueryConfigHandler");
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/GroupQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/GroupQueryNodeProcessor.cs
index fbe6392d45..e806732830 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/GroupQueryNodeProcessor.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/GroupQueryNodeProcessor.cs
@@ -59,7 +59,7 @@ public virtual IQueryNode Process(IQueryNode queryTree)
{
Operator? defaultOperator = GetQueryConfigHandler().Get(ConfigurationKeys.DEFAULT_OPERATOR);
- if (defaultOperator == null)
+ if (defaultOperator is null)
{
throw new ArgumentException(
"DEFAULT_OPERATOR should be set on the QueryConfigHandler");
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/MultiFieldQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/MultiFieldQueryNodeProcessor.cs
index f5ba0e632f..76c5bd1175 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/MultiFieldQueryNodeProcessor.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/MultiFieldQueryNodeProcessor.cs
@@ -71,7 +71,7 @@ protected override IQueryNode PreProcessNode(IQueryNode node)
{
string[] fields = GetQueryConfigHandler().Get(ConfigurationKeys.MULTI_FIELDS);
- if (fields == null)
+ if (fields is null)
{
throw new ArgumentException(
"StandardQueryConfigHandler.ConfigurationKeys.MULTI_FIELDS should be set on the QueryConfigHandler");
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/NumericQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/NumericQueryNodeProcessor.cs
index c1e1ae594f..8475cd724a 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/NumericQueryNodeProcessor.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/NumericQueryNodeProcessor.cs
@@ -89,7 +89,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
{
number = numberFormat.Parse(text);
}
- catch (FormatException e)
+ catch (FormatException e) // LUCENENET: In .NET we are expecting the framework to throw FormatException, not ParseException
{
throw new QueryNodeParseException(new Message(
QueryParserMessages.COULD_NOT_PARSE_NUMBER, fieldNode
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/NumericRangeQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/NumericRangeQueryNodeProcessor.cs
index 784d800176..c1e2dda1d7 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/NumericRangeQueryNodeProcessor.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/NumericRangeQueryNodeProcessor.cs
@@ -87,7 +87,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
{
lowerNumber = numberFormat.Parse(lowerText);
}
- catch (FormatException e)
+ catch (FormatException e) // LUCENENET: In .NET we are expecting the framework to throw FormatException, not ParseException
{
throw new QueryNodeParseException(new Message(
QueryParserMessages.COULD_NOT_PARSE_NUMBER, lower
@@ -101,7 +101,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
{
upperNumber = numberFormat.Parse(upperText);
}
- catch (FormatException e)
+ catch (FormatException e) // LUCENENET: In .NET we are expecting the framework to throw FormatException, not ParseException
{
throw new QueryNodeParseException(new Message(
QueryParserMessages.COULD_NOT_PARSE_NUMBER, upper
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/TermRangeQueryNodeProcessor.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/TermRangeQueryNodeProcessor.cs
index 36fa3f05e2..bcc85d6757 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/TermRangeQueryNodeProcessor.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/Processors/TermRangeQueryNodeProcessor.cs
@@ -140,7 +140,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
}
}
- catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment
+ catch (Exception e) when (e.IsException())
{
// do nothing
}
diff --git a/src/Lucene.Net.QueryParser/Flexible/Standard/QueryParserUtil.cs b/src/Lucene.Net.QueryParser/Flexible/Standard/QueryParserUtil.cs
index 82b3f02bed..6eaf3160d1 100644
--- a/src/Lucene.Net.QueryParser/Flexible/Standard/QueryParserUtil.cs
+++ b/src/Lucene.Net.QueryParser/Flexible/Standard/QueryParserUtil.cs
@@ -43,10 +43,19 @@ public sealed class QueryParserUtil
/// if the length of the queries array differs from the length of the
/// fields array
///
+ ///
+ /// or is null
+ ///
public static Query Parse(string[] queries, string[] fields, Analyzer analyzer)
{
+ // LUCENENET: Added null guard clauses
+ if (queries is null)
+ throw new ArgumentNullException(nameof(queries));
+ if (fields is null)
+ throw new ArgumentNullException(nameof(fields));
+
if (queries.Length != fields.Length)
- throw new ArgumentException("queries.length != fields.length");
+ throw new ArgumentException("queries.Length != fields.Length");
BooleanQuery bQuery = new BooleanQuery();
StandardQueryParser qp = new StandardQueryParser();
@@ -91,11 +100,22 @@ public static Query Parse(string[] queries, string[] fields, Analyzer analyzer)
/// if the length of the fields array differs from the length of the
/// flags array
///
+ ///
+ /// or is null
+ ///
public static Query Parse(string query, string[] fields,
Occur[] flags, Analyzer analyzer)
{
+ // LUCENENET: Added null guard clauses
+ if (query is null)
+ throw new ArgumentNullException(nameof(query));
+ if (fields is null)
+ throw new ArgumentNullException(nameof(fields));
+ if (flags is null)
+ throw new ArgumentNullException(nameof(flags));
+
if (fields.Length != flags.Length)
- throw new ArgumentException("fields.length != flags.length");
+ throw new ArgumentException("fields.Length != flags.Length");
BooleanQuery bQuery = new BooleanQuery();
StandardQueryParser qp = new StandardQueryParser();
@@ -140,9 +160,20 @@ public static Query Parse(string query, string[] fields,
///
/// if the length of the queries, fields, and flags array differ
///
+ ///
+ /// , or is null
+ ///
public static Query Parse(string[] queries, string[] fields,
Occur[] flags, Analyzer analyzer)
{
+ // LUCENENET: Added null guard clauses
+ if (queries is null)
+ throw new ArgumentNullException(nameof(queries));
+ if (fields is null)
+ throw new ArgumentNullException(nameof(fields));
+ if (flags is null)
+ throw new ArgumentNullException(nameof(flags));
+
if (!(queries.Length == fields.Length && queries.Length == flags.Length))
throw new ArgumentException(
"queries, fields, and flags array have have different length");
@@ -168,8 +199,15 @@ public static Query Parse(string[] queries, string[] fields,
/// Returns a string where those characters that TextParser expects to be
/// escaped are escaped by a preceding \.
///
+ ///
+ /// is null
+ ///
public static string Escape(string s)
{
+ // LUCENENET: Added null guard clause
+ if (s is null)
+ throw new ArgumentNullException(nameof(s));
+
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
diff --git a/src/Lucene.Net.QueryParser/Surround/Parser/FastCharStream.cs b/src/Lucene.Net.QueryParser/Surround/Parser/FastCharStream.cs
index b4a2eb671c..16573922e0 100644
--- a/src/Lucene.Net.QueryParser/Surround/Parser/FastCharStream.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Parser/FastCharStream.cs
@@ -120,7 +120,7 @@ public void Done()
{
input.Dispose();
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
Console.Error.WriteLine("Caught: " + e + "; ignoring.");
}
diff --git a/src/Lucene.Net.QueryParser/Surround/Parser/QueryParser.cs b/src/Lucene.Net.QueryParser/Surround/Parser/QueryParser.cs
index 061eaa4522..4c24a9958b 100644
--- a/src/Lucene.Net.QueryParser/Surround/Parser/QueryParser.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Parser/QueryParser.cs
@@ -195,7 +195,7 @@ public SrndQuery TopSrndQuery()
q = FieldsQuery();
Jj_consume_token(0);
{ if (true) return q; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public SrndQuery FieldsQuery()
@@ -205,7 +205,7 @@ public SrndQuery FieldsQuery()
fieldNames = OptionalFields();
q = OrQuery();
{ if (true) return (fieldNames == null) ? q : GetFieldsQuery(q, fieldNames); }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public IList OptionalFields()
@@ -234,7 +234,7 @@ public IList OptionalFields()
}
label_1:
{ if (true) return fieldNames; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public SrndQuery OrQuery()
@@ -267,7 +267,7 @@ public SrndQuery OrQuery()
}
label_2:
{ if (true) return (queries == null) ? q : GetOrQuery(queries, true /* infix */, oprt); }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public SrndQuery AndQuery()
@@ -300,7 +300,7 @@ public SrndQuery AndQuery()
}
label_3:
{ if (true) return (queries == null) ? q : GetAndQuery(queries, true /* infix */, oprt); }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public SrndQuery NotQuery()
@@ -333,7 +333,7 @@ public SrndQuery NotQuery()
}
label_4:
{ if (true) return (queries == null) ? q : GetNotQuery(queries, oprt); }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public SrndQuery NQuery()
@@ -364,7 +364,7 @@ public SrndQuery NQuery()
}
label_5:
{ if (true) return q; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public SrndQuery WQuery()
@@ -395,7 +395,7 @@ public SrndQuery WQuery()
}
label_6:
{ if (true) return q; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public SrndQuery PrimaryQuery()
@@ -429,7 +429,7 @@ public SrndQuery PrimaryQuery()
}
OptionalWeights(q);
{ if (true) return q; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public SrndQuery PrefixOperatorQuery()
@@ -467,7 +467,7 @@ public SrndQuery PrefixOperatorQuery()
Jj_consume_token(-1);
throw new ParseException();
}
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public IList FieldsQueryList()
@@ -496,7 +496,7 @@ public IList FieldsQueryList()
label_7:
Jj_consume_token(RegexpToken.RPAREN);
{ if (true) return queries; }
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public SrndQuery SimpleTerm()
@@ -544,7 +544,7 @@ public SrndQuery SimpleTerm()
Jj_consume_token(-1);
throw new ParseException();
}
- throw new Exception("Missing return statement in function");
+ throw Error.Create("Missing return statement in function");
}
public void OptionalWeights(SrndQuery q)
@@ -569,7 +569,7 @@ public void OptionalWeights(SrndQuery q)
// LUCENENET TODO: Test parsing float in various cultures (.NET)
f = float.Parse(weight.Image);
}
- catch (Exception floatExc)
+ catch (Exception floatExc) // LUCENENET: No need to call the IsException() extension method here because we are dealing only with a .NET platform method
{
{ if (true) throw new ParseException(boostErrorMessage + weight.Image + " (" + floatExc + ")", floatExc); }
}
diff --git a/src/Lucene.Net.QueryParser/Surround/Parser/QueryParserTokenManager.cs b/src/Lucene.Net.QueryParser/Surround/Parser/QueryParserTokenManager.cs
index af7fea8b6c..164fc8dbb2 100644
--- a/src/Lucene.Net.QueryParser/Surround/Parser/QueryParserTokenManager.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Parser/QueryParserTokenManager.cs
@@ -1,4 +1,5 @@
using Lucene.Net.Support.IO;
+using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
@@ -432,7 +433,7 @@ private int JjMoveNfa_1(int startState, int curPos)
if ((i = jjnewStateCnt) == (startsAt = 38 - (jjnewStateCnt = startsAt)))
return curPos;
try { m_curChar = m_input_stream.ReadChar(); }
- catch (IOException /*e*/) { return curPos; }
+ catch (Exception e) when (e.IsIOException()) { return curPos; }
}
}
@@ -519,7 +520,7 @@ private int JjMoveNfa_0(int startState, int curPos)
if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
return curPos;
try { m_curChar = m_input_stream.ReadChar(); }
- catch (IOException /*e*/) { return curPos; }
+ catch (Exception e) when (e.IsIOException()) { return curPos; }
}
}
internal static readonly int[] jjnextStates = {
@@ -661,7 +662,7 @@ public virtual Token GetNextToken()
{
m_curChar = m_input_stream.BeginToken();
}
- catch (IOException /*e*/)
+ catch (Exception e) when (e.IsIOException())
{
jjmatchedKind = 0;
matchedToken = JjFillToken();
@@ -704,7 +705,7 @@ public virtual Token GetNextToken()
string error_after = null;
bool EOFSeen = false;
try { m_input_stream.ReadChar(); m_input_stream.BackUp(1); }
- catch (IOException /*e1*/)
+ catch (Exception e1) when (e1.IsIOException())
{
EOFSeen = true;
error_after = curPos <= 1 ? "" : m_input_stream.Image;
diff --git a/src/Lucene.Net.QueryParser/Surround/Parser/TokenMgrError.cs b/src/Lucene.Net.QueryParser/Surround/Parser/TokenMgrError.cs
index b5b28b8499..2f42f05d7b 100644
--- a/src/Lucene.Net.QueryParser/Surround/Parser/TokenMgrError.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Parser/TokenMgrError.cs
@@ -30,7 +30,7 @@ namespace Lucene.Net.QueryParsers.Surround.Parser
#if FEATURE_SERIALIZABLE_EXCEPTIONS
[Serializable]
#endif
- public class TokenMgrError : Exception
+ public class TokenMgrError : Exception, IError // LUCENENET specific: Added IError for identification of the Java superclass in .NET
{
/*
* Ordinals for various reasons why an Error of this type can be thrown.
diff --git a/src/Lucene.Net.QueryParser/Surround/Query/ComposedQuery.cs b/src/Lucene.Net.QueryParser/Surround/Query/ComposedQuery.cs
index 56138f938e..1c154c4553 100644
--- a/src/Lucene.Net.QueryParser/Surround/Query/ComposedQuery.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Query/ComposedQuery.cs
@@ -1,4 +1,5 @@
-using System;
+using Lucene.Net.Diagnostics;
+using System;
using System.Collections.Generic;
using System.Text;
@@ -35,7 +36,7 @@ protected ComposedQuery(IList qs, bool operatorInfix, string opName)
protected virtual void Recompose(IList queries)
{
- if (queries.Count < 2) throw new InvalidOperationException("Too few subqueries");
+ if (queries.Count < 2) throw AssertionError.Create("Too few subqueries");
this.m_queries = new List(queries);
}
diff --git a/src/Lucene.Net.QueryParser/Surround/Query/RewriteQuery.cs b/src/Lucene.Net.QueryParser/Surround/Query/RewriteQuery.cs
index c9857f550d..473e3cfacf 100644
--- a/src/Lucene.Net.QueryParser/Surround/Query/RewriteQuery.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Query/RewriteQuery.cs
@@ -79,7 +79,7 @@ public override bool Equals(object obj)
/// throws always: clone is not supported.
public override object Clone()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
}
diff --git a/src/Lucene.Net.QueryParser/Surround/Query/SpanNearClauseFactory.cs b/src/Lucene.Net.QueryParser/Surround/Query/SpanNearClauseFactory.cs
index abded9ce14..98d8e81e35 100644
--- a/src/Lucene.Net.QueryParser/Surround/Query/SpanNearClauseFactory.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Query/SpanNearClauseFactory.cs
@@ -1,4 +1,5 @@
-using Lucene.Net.Index;
+using Lucene.Net.Diagnostics;
+using Lucene.Net.Index;
using Lucene.Net.Search.Spans;
using System;
using System.Collections.Generic;
@@ -105,7 +106,7 @@ public virtual void AddSpanQuery(Search.Query q)
if (q == SrndQuery.TheEmptyLcnQuery)
return;
if (!(q is SpanQuery))
- throw new InvalidOperationException("Expected SpanQuery: " + q.ToString(FieldName));
+ throw AssertionError.Create("Expected SpanQuery: " + q.ToString(FieldName));
AddSpanQueryWeighted((SpanQuery)q, q.Boost);
}
diff --git a/src/Lucene.Net.QueryParser/Surround/Query/SrndBooleanQuery.cs b/src/Lucene.Net.QueryParser/Surround/Query/SrndBooleanQuery.cs
index 9dd5dd93c5..11ca8e7da0 100644
--- a/src/Lucene.Net.QueryParser/Surround/Query/SrndBooleanQuery.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Query/SrndBooleanQuery.cs
@@ -1,4 +1,5 @@
-using Lucene.Net.Search;
+using Lucene.Net.Diagnostics;
+using Lucene.Net.Search;
using System;
using System.Collections.Generic;
@@ -40,7 +41,7 @@ public static Search.Query MakeBooleanQuery(
{
if (queries.Count <= 1)
{
- throw new InvalidOperationException("Too few subqueries: " + queries.Count);
+ throw AssertionError.Create("Too few subqueries: " + queries.Count);
}
BooleanQuery bq = new BooleanQuery();
AddQueriesToBoolean(bq, queries, occur);
diff --git a/src/Lucene.Net.QueryParser/Surround/Query/SrndQuery.cs b/src/Lucene.Net.QueryParser/Surround/Query/SrndQuery.cs
index 8440bcdda9..1f62f4b2f5 100644
--- a/src/Lucene.Net.QueryParser/Surround/Query/SrndQuery.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Query/SrndQuery.cs
@@ -118,17 +118,17 @@ internal sealed class EmptyLcnQuery : BooleanQuery
public override float Boost
{
get => base.Boost;
- set => throw new NotSupportedException();
+ set => throw UnsupportedOperationException.Create();
}
public override void Add(BooleanClause clause)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
public override void Add(Search.Query query, Occur occur)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
}
diff --git a/src/Lucene.Net.QueryParser/Surround/Query/TooManyBasicQueries.cs b/src/Lucene.Net.QueryParser/Surround/Query/TooManyBasicQueries.cs
index c5024ee641..0f5c6df9ab 100644
--- a/src/Lucene.Net.QueryParser/Surround/Query/TooManyBasicQueries.cs
+++ b/src/Lucene.Net.QueryParser/Surround/Query/TooManyBasicQueries.cs
@@ -38,12 +38,13 @@ public TooManyBasicQueries(int maxBasicQueries)
: base("Exceeded maximum of " + maxBasicQueries + " basic queries.")
{ }
-#if FEATURE_SERIALIZABLE_EXCEPTIONS
- // For testing
- public TooManyBasicQueries(string message)
+ // LUCENENET: For testing purposes
+ internal TooManyBasicQueries(string message)
: base(message)
- { }
+ {
+ }
+#if FEATURE_SERIALIZABLE_EXCEPTIONS
///
/// Initializes a new instance of this class with serialized data.
///
diff --git a/src/Lucene.Net.QueryParser/Xml/Builders/LikeThisQueryBuilder.cs b/src/Lucene.Net.QueryParser/Xml/Builders/LikeThisQueryBuilder.cs
index b576373725..de2736e0cb 100644
--- a/src/Lucene.Net.QueryParser/Xml/Builders/LikeThisQueryBuilder.cs
+++ b/src/Lucene.Net.QueryParser/Xml/Builders/LikeThisQueryBuilder.cs
@@ -87,9 +87,9 @@ public virtual Query GetQuery(XmlElement e)
}
ts.End();
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new ParserException("IoException parsing stop words list in "
+ throw new ParserException("IOException parsing stop words list in "
+ GetType().Name + ":" + ioe.Message);
}
finally
diff --git a/src/Lucene.Net.QueryParser/Xml/Builders/NumericRangeFilterBuilder.cs b/src/Lucene.Net.QueryParser/Xml/Builders/NumericRangeFilterBuilder.cs
index 443291c67f..51363580da 100644
--- a/src/Lucene.Net.QueryParser/Xml/Builders/NumericRangeFilterBuilder.cs
+++ b/src/Lucene.Net.QueryParser/Xml/Builders/NumericRangeFilterBuilder.cs
@@ -150,7 +150,7 @@ public virtual Filter GetFilter(XmlElement e)
}
return filter;
}
- catch (FormatException nfe)
+ catch (Exception nfe) when (nfe.IsNumberFormatException())
{
if (strictMode)
{
diff --git a/src/Lucene.Net.QueryParser/Xml/Builders/NumericRangeQueryBuilder.cs b/src/Lucene.Net.QueryParser/Xml/Builders/NumericRangeQueryBuilder.cs
index 80f1bae71f..de221ee41b 100644
--- a/src/Lucene.Net.QueryParser/Xml/Builders/NumericRangeQueryBuilder.cs
+++ b/src/Lucene.Net.QueryParser/Xml/Builders/NumericRangeQueryBuilder.cs
@@ -128,7 +128,7 @@ public virtual Query GetQuery(XmlElement e)
}
return filter;
}
- catch (FormatException nfe)
+ catch (Exception nfe) when (nfe.IsNumberFormatException())
{
throw new ParserException("Could not parse lowerTerm or upperTerm into a number", nfe);
}
diff --git a/src/Lucene.Net.QueryParser/Xml/Builders/SpanOrTermsBuilder.cs b/src/Lucene.Net.QueryParser/Xml/Builders/SpanOrTermsBuilder.cs
index 621d7102aa..086df81589 100644
--- a/src/Lucene.Net.QueryParser/Xml/Builders/SpanOrTermsBuilder.cs
+++ b/src/Lucene.Net.QueryParser/Xml/Builders/SpanOrTermsBuilder.cs
@@ -3,6 +3,7 @@
using Lucene.Net.Index;
using Lucene.Net.Search.Spans;
using Lucene.Net.Util;
+using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
@@ -63,7 +64,7 @@ public override SpanQuery GetSpanQuery(XmlElement e)
soq.Boost = DOMUtils.GetAttribute(e, "boost", 1.0f);
return soq;
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
throw new ParserException("IOException parsing value:" + value, ioe);
}
diff --git a/src/Lucene.Net.QueryParser/Xml/Builders/TermsFilterBuilder.cs b/src/Lucene.Net.QueryParser/Xml/Builders/TermsFilterBuilder.cs
index 5222553722..07ac660305 100644
--- a/src/Lucene.Net.QueryParser/Xml/Builders/TermsFilterBuilder.cs
+++ b/src/Lucene.Net.QueryParser/Xml/Builders/TermsFilterBuilder.cs
@@ -63,9 +63,9 @@ public virtual Filter GetFilter(XmlElement e)
}
ts.End();
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new Exception("Error constructing terms from index:" + ioe, ioe);
+ throw RuntimeException.Create("Error constructing terms from index:" + ioe, ioe);
}
finally
{
diff --git a/src/Lucene.Net.QueryParser/Xml/Builders/TermsQueryBuilder.cs b/src/Lucene.Net.QueryParser/Xml/Builders/TermsQueryBuilder.cs
index e026f8688f..326cae490d 100644
--- a/src/Lucene.Net.QueryParser/Xml/Builders/TermsQueryBuilder.cs
+++ b/src/Lucene.Net.QueryParser/Xml/Builders/TermsQueryBuilder.cs
@@ -61,9 +61,9 @@ public virtual Query GetQuery(XmlElement e)
}
ts.End();
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new Exception("Error constructing terms from index:" + ioe, ioe);
+ throw RuntimeException.Create("Error constructing terms from index:" + ioe, ioe);
}
finally
{
diff --git a/src/Lucene.Net.QueryParser/Xml/Builders/UserInputQueryBuilder.cs b/src/Lucene.Net.QueryParser/Xml/Builders/UserInputQueryBuilder.cs
index ea3883efe3..992e361ba9 100644
--- a/src/Lucene.Net.QueryParser/Xml/Builders/UserInputQueryBuilder.cs
+++ b/src/Lucene.Net.QueryParser/Xml/Builders/UserInputQueryBuilder.cs
@@ -80,7 +80,7 @@ public virtual Query GetQuery(XmlElement e)
q.Boost = DOMUtils.GetAttribute(e, "boost", 1.0f);
return q;
}
- catch (ParseException e1)
+ catch (Lucene.Net.QueryParsers.Classic.ParseException e1) // LUCENENET: Classic QueryParser has its own ParseException that is different than the one in Support
{
throw new ParserException(e1.Message, e1);
}
diff --git a/src/Lucene.Net.QueryParser/Xml/CoreParser.cs b/src/Lucene.Net.QueryParser/Xml/CoreParser.cs
index dfc6859cbb..c6fbb8523d 100644
--- a/src/Lucene.Net.QueryParser/Xml/CoreParser.cs
+++ b/src/Lucene.Net.QueryParser/Xml/CoreParser.cs
@@ -158,7 +158,7 @@ private static XmlDocument ParseXML(Stream pXmlFile)
{
doc.Load(pXmlFile);
}
- catch (Exception se)
+ catch (Exception se) // LUCENENET: No need to call the IsException() extension method here because we are dealing only with a .NET platform method
{
throw new ParserException("Error parsing XML stream:" + se, se);
}
@@ -173,7 +173,7 @@ private static XmlDocument ParseXML(TextReader pXmlFile)
{
doc.Load(pXmlFile);
}
- catch (Exception se)
+ catch (Exception se) // LUCENENET: No need to call the IsException() extension method here because we are dealing only with a .NET platform method
{
throw new ParserException("Error parsing XML stream:" + se, se);
}
@@ -188,7 +188,7 @@ private static XmlDocument ParseXML(XmlReader pXmlFile)
{
doc.Load(pXmlFile);
}
- catch (Exception se)
+ catch (Exception se) // LUCENENET: No need to call the IsException() extension method here because we are dealing only with a .NET platform method
{
throw new ParserException("Error parsing XML stream:" + se, se);
}
diff --git a/src/Lucene.Net.QueryParser/Xml/DOMUtils.cs b/src/Lucene.Net.QueryParser/Xml/DOMUtils.cs
index 0cff1f937f..a1bb11b2be 100644
--- a/src/Lucene.Net.QueryParser/Xml/DOMUtils.cs
+++ b/src/Lucene.Net.QueryParser/Xml/DOMUtils.cs
@@ -226,9 +226,9 @@ public static XmlDocument LoadXML(TextReader input)
{
result.Load(input);
}
- catch (Exception se)
+ catch (Exception se) // LUCENENET: No need to call the IsException() extension method here because we are dealing only with a .NET platform method
{
- throw new Exception("Error parsing file:" + se, se);
+ throw RuntimeException.Create("Error parsing file:" + se, se);
}
return result;
}
@@ -246,9 +246,9 @@ public static XmlDocument LoadXML(Stream input)
{
result.Load(input);
}
- catch (Exception se)
+ catch (Exception se) // LUCENENET: No need to call the IsException() extension method here because we are dealing only with a .NET platform method
{
- throw new Exception("Error parsing file:" + se, se);
+ throw RuntimeException.Create("Error parsing file:" + se, se);
}
return result;
}
@@ -266,9 +266,9 @@ public static XmlDocument LoadXML(XmlReader input)
{
result.Load(input);
}
- catch (Exception se)
+ catch (Exception se) // LUCENENET: No need to call the IsException() extension method here because we are dealing only with a .NET platform method
{
- throw new Exception("Error parsing file:" + se, se);
+ throw RuntimeException.Create("Error parsing file:" + se, se);
}
return result;
}
diff --git a/src/Lucene.Net.QueryParser/Xml/ParserException.cs b/src/Lucene.Net.QueryParser/Xml/ParserException.cs
index 5dfb151ad1..e1c9bf7b9d 100644
--- a/src/Lucene.Net.QueryParser/Xml/ParserException.cs
+++ b/src/Lucene.Net.QueryParser/Xml/ParserException.cs
@@ -38,12 +38,12 @@ public ParserException()
{
}
- public ParserException(String message)
+ public ParserException(string message)
: base(message)
{
}
- public ParserException(String message, Exception cause)
+ public ParserException(string message, Exception cause)
: base(message, cause)
{
}
diff --git a/src/Lucene.Net.Replicator/Http/HttpClientBase.cs b/src/Lucene.Net.Replicator/Http/HttpClientBase.cs
index 0a3a328556..0af893e046 100644
--- a/src/Lucene.Net.Replicator/Http/HttpClientBase.cs
+++ b/src/Lucene.Net.Replicator/Http/HttpClientBase.cs
@@ -120,7 +120,7 @@ protected void EnsureOpen()
{
if (IsDisposed)
{
- throw new ObjectDisposedException("HttpClient already disposed");
+ throw AlreadyClosedException.Create(this.GetType().FullName, "HttpClient already disposed.");
}
}
diff --git a/src/Lucene.Net.Replicator/Http/HttpReplicator.cs b/src/Lucene.Net.Replicator/Http/HttpReplicator.cs
index fa50fe3dc8..5c4f98cd9d 100644
--- a/src/Lucene.Net.Replicator/Http/HttpReplicator.cs
+++ b/src/Lucene.Net.Replicator/Http/HttpReplicator.cs
@@ -94,7 +94,7 @@ public virtual Stream ObtainFile(string sessionId, string source, string fileNam
/// this replicator implementation does not support remote publishing of revisions
public virtual void Publish(IRevision revision)
{
- throw new NotSupportedException("this replicator implementation does not support remote publishing of revisions");
+ throw UnsupportedOperationException.Create("this replicator implementation does not support remote publishing of revisions");
}
///
diff --git a/src/Lucene.Net.Replicator/Http/ReplicationService.cs b/src/Lucene.Net.Replicator/Http/ReplicationService.cs
index 90e20cdafe..8187362bc8 100644
--- a/src/Lucene.Net.Replicator/Http/ReplicationService.cs
+++ b/src/Lucene.Net.Replicator/Http/ReplicationService.cs
@@ -120,7 +120,7 @@ private static string ExtractRequestParam(IReplicationRequest request, string pa
string param = request.QueryParam(paramName);
if (param == null)
{
- throw new InvalidOperationException("Missing mandatory parameter: " + paramName);
+ throw IllegalStateException.Create("Missing mandatory parameter: " + paramName);
}
return param;
}
@@ -136,17 +136,17 @@ public virtual void Perform(IReplicationRequest request, IReplicationResponse re
string[] pathElements = GetPathElements(request);
if (pathElements.Length != 2)
{
- throw new InvalidOperationException("invalid path, must contain shard ID and action, e.g. */s1/update");
+ throw IllegalStateException.Create("invalid path, must contain shard ID and action, e.g. */s1/update");
}
if (!Enum.TryParse(pathElements[ACTION_IDX], true, out ReplicationAction action))
{
- throw new InvalidOperationException("Unsupported action provided: " + pathElements[ACTION_IDX]);
+ throw IllegalStateException.Create("Unsupported action provided: " + pathElements[ACTION_IDX]);
}
if (!replicators.TryGetValue(pathElements[SHARD_IDX], out IReplicator replicator))
{
- throw new InvalidOperationException("unrecognized shard ID " + pathElements[SHARD_IDX]);
+ throw IllegalStateException.Create("unrecognized shard ID " + pathElements[SHARD_IDX]);
}
// SOLR-8933 Don't close this stream.
diff --git a/src/Lucene.Net.Replicator/IndexAndTaxonomyReplicationHandler.cs b/src/Lucene.Net.Replicator/IndexAndTaxonomyReplicationHandler.cs
index a65e7c9b4c..13a63e8871 100644
--- a/src/Lucene.Net.Replicator/IndexAndTaxonomyReplicationHandler.cs
+++ b/src/Lucene.Net.Replicator/IndexAndTaxonomyReplicationHandler.cs
@@ -73,7 +73,7 @@ public IndexAndTaxonomyReplicationHandler(Directory indexDirectory, Directory ta
bool taxonomyExists = DirectoryReader.IndexExists(taxonomyDirectory);
if (indexExists != taxonomyExists)
- throw new InvalidOperationException(string.Format("search and taxonomy indexes must either both exist or not: index={0} taxo={1}", indexExists, taxonomyExists));
+ throw IllegalStateException.Create(string.Format("search and taxonomy indexes must either both exist or not: index={0} taxo={1}", indexExists, taxonomyExists));
if (indexExists)
{
diff --git a/src/Lucene.Net.Replicator/IndexInputInputStream.cs b/src/Lucene.Net.Replicator/IndexInputInputStream.cs
index 6a4a944c66..41f31b5bb8 100644
--- a/src/Lucene.Net.Replicator/IndexInputInputStream.cs
+++ b/src/Lucene.Net.Replicator/IndexInputInputStream.cs
@@ -38,7 +38,7 @@ public IndexInputStream(IndexInput input)
public override void Flush()
{
- throw new InvalidOperationException("Cannot flush a readonly stream.");
+ throw IllegalStateException.Create("Cannot flush a readonly stream."); // LUCENENET TODO: Change to NotSupportedException ?
}
public override long Seek(long offset, SeekOrigin origin)
@@ -60,7 +60,7 @@ public override long Seek(long offset, SeekOrigin origin)
public override void SetLength(long value)
{
- throw new InvalidOperationException("Cannot change length of a readonly stream.");
+ throw IllegalStateException.Create("Cannot change length of a readonly stream."); // LUCENENET TODO: Change to NotSupportedException ?
}
public override int Read(byte[] buffer, int offset, int count)
@@ -73,7 +73,7 @@ public override int Read(byte[] buffer, int offset, int count)
public override void Write(byte[] buffer, int offset, int count)
{
- throw new InvalidCastException("Cannot write to a readonly stream.");
+ throw new InvalidCastException("Cannot write to a readonly stream."); // LUCENENET TODO: Change to NotSupportedException ?
}
public override bool CanRead => true;
diff --git a/src/Lucene.Net.Replicator/IndexReplicationHandler.cs b/src/Lucene.Net.Replicator/IndexReplicationHandler.cs
index f9b8438580..ba2f4054d6 100644
--- a/src/Lucene.Net.Replicator/IndexReplicationHandler.cs
+++ b/src/Lucene.Net.Replicator/IndexReplicationHandler.cs
@@ -112,7 +112,7 @@ public static string GetSegmentsFile(IList files, bool allowEmpty)
{
if (allowEmpty)
return null;
- throw new InvalidOperationException("empty list of files not allowed");
+ throw IllegalStateException.Create("empty list of files not allowed");
}
string segmentsFile = files[files.Count - 1];
@@ -120,7 +120,7 @@ public static string GetSegmentsFile(IList files, bool allowEmpty)
files.RemoveAt(files.Count - 1);
if (!segmentsFile.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal) || segmentsFile.Equals(IndexFileNames.SEGMENTS_GEN, StringComparison.Ordinal))
{
- throw new InvalidOperationException(
+ throw IllegalStateException.Create(
string.Format("last file to copy+sync must be segments_N but got {0}; check your Revision implementation!", segmentsFile));
}
return segmentsFile;
diff --git a/src/Lucene.Net.Replicator/LocalReplicator.cs b/src/Lucene.Net.Replicator/LocalReplicator.cs
index 82e95ab0b5..4b12e69b86 100644
--- a/src/Lucene.Net.Replicator/LocalReplicator.cs
+++ b/src/Lucene.Net.Replicator/LocalReplicator.cs
@@ -1,4 +1,4 @@
-using J2N.Threading.Atomic;
+using J2N.Threading.Atomic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -59,7 +59,7 @@ public virtual void DecRef()
{
if (refCount <= 0)
{
- throw new InvalidOperationException("this revision is already released");
+ throw IllegalStateException.Create("this revision is already released");
}
var rc = refCount.DecrementAndGet();
@@ -82,7 +82,7 @@ public virtual void DecRef()
}
else if (rc < 0)
{
- throw new InvalidOperationException(string.Format("too many decRef calls: refCount is {0} after decrement", rc));
+ throw IllegalStateException.Create(string.Format("too many decRef calls: refCount is {0} after decrement", rc));
}
}
@@ -164,7 +164,7 @@ protected void EnsureOpen()
if (!disposed)
return;
- throw new ObjectDisposedException("This replicator has already been disposed");
+ throw AlreadyClosedException.Create(this.GetType().FullName, "This replicator has already been disposed.");
}
}
diff --git a/src/Lucene.Net.Replicator/ReplicationClient.cs b/src/Lucene.Net.Replicator/ReplicationClient.cs
index c6703f79ec..51c07d5e5e 100644
--- a/src/Lucene.Net.Replicator/ReplicationClient.cs
+++ b/src/Lucene.Net.Replicator/ReplicationClient.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Store;
+using Lucene.Net.Store;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using System;
@@ -320,7 +320,7 @@ protected void EnsureOpen()
if (!disposed)
return;
- throw new ObjectDisposedException("this update client has already been closed");
+ throw AlreadyClosedException.Create(this.GetType().FullName, "this update client has already been disposed.");
}
// LUCENENET specific Utility Method
@@ -411,7 +411,7 @@ public virtual void StartUpdateThread(long intervalMillis, string threadName)
{
EnsureOpen();
if (updateThread != null && updateThread.IsAlive)
- throw new InvalidOperationException("cannot start an update thread when one is running, must first call 'stopUpdateThread()'");
+ throw IllegalStateException.Create("cannot start an update thread when one is running, must first call 'stopUpdateThread()'");
threadName = threadName == null ? INFO_STREAM_COMPONENT : "ReplicationThread-" + threadName;
updateThread = new ReplicationThread(intervalMillis, threadName, DoUpdate, HandleUpdateException, updateLock);
diff --git a/src/Lucene.Net.Sandbox/Queries/SlowFuzzyQuery.cs b/src/Lucene.Net.Sandbox/Queries/SlowFuzzyQuery.cs
index 5b935cc49d..770166685f 100644
--- a/src/Lucene.Net.Sandbox/Queries/SlowFuzzyQuery.cs
+++ b/src/Lucene.Net.Sandbox/Queries/SlowFuzzyQuery.cs
@@ -85,11 +85,11 @@ public SlowFuzzyQuery(Term term, float minimumSimilarity, int prefixLength,
if (minimumSimilarity >= 1.0f && minimumSimilarity != (int)minimumSimilarity)
throw new ArgumentException("fractional edit distances are not allowed");
if (minimumSimilarity < 0.0f)
- throw new ArgumentException("minimumSimilarity < 0");
+ throw new ArgumentOutOfRangeException(nameof(minimumSimilarity), "minimumSimilarity < 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
if (prefixLength < 0)
- throw new ArgumentException("prefixLength < 0");
+ throw new ArgumentOutOfRangeException(nameof(prefixLength), "prefixLength < 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
if (maxExpansions < 0)
- throw new ArgumentException("maxExpansions < 0");
+ throw new ArgumentOutOfRangeException(nameof(maxExpansions), "maxExpansions < 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
MultiTermRewriteMethod = new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(maxExpansions);
diff --git a/src/Lucene.Net.Sandbox/Queries/SortedSetSortField.cs b/src/Lucene.Net.Sandbox/Queries/SortedSetSortField.cs
index 50cd15f205..40896e498e 100644
--- a/src/Lucene.Net.Sandbox/Queries/SortedSetSortField.cs
+++ b/src/Lucene.Net.Sandbox/Queries/SortedSetSortField.cs
@@ -161,7 +161,7 @@ protected override SortedDocValues GetSortedDocValues(AtomicReaderContext contex
if (sortedSet.ValueCount >= int.MaxValue)
{
- throw new NotSupportedException("fields containing more than " + (int.MaxValue - 1) + " unique terms are unsupported");
+ throw UnsupportedOperationException.Create("fields containing more than " + (int.MaxValue - 1) + " unique terms are unsupported");
}
SortedDocValues singleton = DocValues.UnwrapSingleton(sortedSet);
@@ -180,7 +180,7 @@ protected override SortedDocValues GetSortedDocValues(AtomicReaderContext contex
{
if (sortedSet is RandomAccessOrds == false)
{
- throw new NotSupportedException("codec does not support random access ordinals, cannot use selector: " + outerInstance.selector);
+ throw UnsupportedOperationException.Create("codec does not support random access ordinals, cannot use selector: " + outerInstance.selector);
}
RandomAccessOrds randomOrds = (RandomAccessOrds)sortedSet;
switch (outerInstance.selector)
@@ -190,8 +190,7 @@ protected override SortedDocValues GetSortedDocValues(AtomicReaderContext contex
case Selector.MIDDLE_MAX: return new MiddleMaxValue(randomOrds);
case Selector.MIN:
default:
- if (Debugging.AssertsEnabled) Debugging.Assert(false);
- return null;
+ throw AssertionError.Create();
}
}
}
diff --git a/src/Lucene.Net.Spatial/DisjointSpatialFilter.cs b/src/Lucene.Net.Spatial/DisjointSpatialFilter.cs
index 5de32552b1..243bfb07d5 100644
--- a/src/Lucene.Net.Spatial/DisjointSpatialFilter.cs
+++ b/src/Lucene.Net.Spatial/DisjointSpatialFilter.cs
@@ -107,7 +107,7 @@ public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDo
int maxDoc = context.AtomicReader.MaxDoc;
if (docsWithField.Length != maxDoc)
{
- throw new InvalidOperationException("Bits length should be maxDoc (" + maxDoc + ") but wasn't: " + docsWithField);
+ throw IllegalStateException.Create("Bits length should be maxDoc (" + maxDoc + ") but wasn't: " + docsWithField);
}
if (docsWithField is Bits.MatchNoBits)
diff --git a/src/Lucene.Net.Spatial/Prefix/AbstractVisitingPrefixTreeFilter.cs b/src/Lucene.Net.Spatial/Prefix/AbstractVisitingPrefixTreeFilter.cs
index ac98287fdb..0279687679 100644
--- a/src/Lucene.Net.Spatial/Prefix/AbstractVisitingPrefixTreeFilter.cs
+++ b/src/Lucene.Net.Spatial/Prefix/AbstractVisitingPrefixTreeFilter.cs
@@ -257,7 +257,7 @@ private void AddIntersectingChildren()
Cell cell = curVNode.cell;
if (cell.Level >= m_outerInstance.m_detailLevel)
{
- throw new InvalidOperationException("Spatial logic error");
+ throw IllegalStateException.Create("Spatial logic error");
}
//Check for adjacent leaf (happens for indexed non-point shapes)
if (m_hasIndexedLeaves && cell.Level != 0)
diff --git a/src/Lucene.Net.Spatial/Prefix/Tree/Cell.cs b/src/Lucene.Net.Spatial/Prefix/Tree/Cell.cs
index 3acf138aaa..068542e92d 100644
--- a/src/Lucene.Net.Spatial/Prefix/Tree/Cell.cs
+++ b/src/Lucene.Net.Spatial/Prefix/Tree/Cell.cs
@@ -163,7 +163,7 @@ public virtual byte[] GetTokenBytes()
{
if (b_off != 0 || b_len != bytes.Length)
{
- throw new InvalidOperationException("Not supported if byte[] needs to be recreated.");
+ throw IllegalStateException.Create("Not supported if byte[] needs to be recreated.");
}
}
else
diff --git a/src/Lucene.Net.Spatial/Prefix/Tree/GeohashPrefixTree.cs b/src/Lucene.Net.Spatial/Prefix/Tree/GeohashPrefixTree.cs
index 957653c0cb..ea315eb1ee 100644
--- a/src/Lucene.Net.Spatial/Prefix/Tree/GeohashPrefixTree.cs
+++ b/src/Lucene.Net.Spatial/Prefix/Tree/GeohashPrefixTree.cs
@@ -1,4 +1,4 @@
-using Spatial4n.Core.Context;
+using Spatial4n.Core.Context;
using Spatial4n.Core.Shapes;
using Spatial4n.Core.Util;
using System;
@@ -65,7 +65,7 @@ public GeohashPrefixTree(SpatialContext ctx, int maxLevels)
int Maxp = MaxLevelsPossible;
if (maxLevels <= 0 || maxLevels > Maxp)
{
- throw new ArgumentException("maxLen must be [1-" + Maxp + "] but got " + maxLevels);
+ throw new ArgumentOutOfRangeException(nameof(maxLevels), "maxLen must be [1-" + Maxp + "] but got " + maxLevels); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
}
diff --git a/src/Lucene.Net.Spatial/Prefix/Tree/QuadPrefixTree.cs b/src/Lucene.Net.Spatial/Prefix/Tree/QuadPrefixTree.cs
index b69a180b73..bc35b9f7d4 100644
--- a/src/Lucene.Net.Spatial/Prefix/Tree/QuadPrefixTree.cs
+++ b/src/Lucene.Net.Spatial/Prefix/Tree/QuadPrefixTree.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Diagnostics;
+using Lucene.Net.Diagnostics;
using Spatial4n.Core.Context;
using Spatial4n.Core.Shapes;
using System;
@@ -319,7 +319,7 @@ private IRectangle MakeShape()
}
else
{
- throw new Exception("unexpected char: " + c);
+ throw RuntimeException.Create("unexpected char: " + c);
}
}
int len = token.Length;
diff --git a/src/Lucene.Net.Spatial/Prefix/Tree/SpatialPrefixTree.cs b/src/Lucene.Net.Spatial/Prefix/Tree/SpatialPrefixTree.cs
index a80f9d9455..655a6c0629 100644
--- a/src/Lucene.Net.Spatial/Prefix/Tree/SpatialPrefixTree.cs
+++ b/src/Lucene.Net.Spatial/Prefix/Tree/SpatialPrefixTree.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Diagnostics;
+using Lucene.Net.Diagnostics;
using Spatial4n.Core.Context;
using Spatial4n.Core.Shapes;
using System;
@@ -92,7 +92,7 @@ public virtual double GetDistanceForLevel(int level)
{
if (level < 1 || level > MaxLevels)
{
- throw new ArgumentException("Level must be in 1 to maxLevels range");
+ throw new ArgumentOutOfRangeException(nameof(level), "Level must be in 1 to maxLevels range"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
//TODO cache for each level
Cell cell = GetCell(m_ctx.WorldBounds.Center, level);
diff --git a/src/Lucene.Net.Spatial/Prefix/Tree/SpatialPrefixTreeFactory.cs b/src/Lucene.Net.Spatial/Prefix/Tree/SpatialPrefixTreeFactory.cs
index 54f87029ff..da0ce34a13 100644
--- a/src/Lucene.Net.Spatial/Prefix/Tree/SpatialPrefixTreeFactory.cs
+++ b/src/Lucene.Net.Spatial/Prefix/Tree/SpatialPrefixTreeFactory.cs
@@ -1,4 +1,4 @@
-using Spatial4n.Core.Context;
+using Spatial4n.Core.Context;
using Spatial4n.Core.Distance;
using System;
using System.Collections.Generic;
@@ -67,9 +67,9 @@ public static SpatialPrefixTree MakeSPT(IDictionary args, Spatia
Type c = Type.GetType(cname);
instance = (SpatialPrefixTreeFactory)Activator.CreateInstance(c);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
instance.Init(args, ctx);
diff --git a/src/Lucene.Net.Spatial/Prefix/WithinPrefixTreeFilter.cs b/src/Lucene.Net.Spatial/Prefix/WithinPrefixTreeFilter.cs
index c1ea3f6567..d61fc1019a 100644
--- a/src/Lucene.Net.Spatial/Prefix/WithinPrefixTreeFilter.cs
+++ b/src/Lucene.Net.Spatial/Prefix/WithinPrefixTreeFilter.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Diagnostics;
+using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Spatial.Prefix.Tree;
@@ -81,7 +81,7 @@ protected virtual IShape BufferShape(IShape shape, double distErr)
//TODO move this generic code elsewhere? Spatial4j?
if (distErr <= 0)
{
- throw new ArgumentException("distErr must be > 0");
+ throw new ArgumentOutOfRangeException(nameof(distErr), "distErr must be > 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
SpatialContext ctx = m_grid.SpatialContext;
if (shape is IPoint point)
diff --git a/src/Lucene.Net.Spatial/Query/SpatialArgs.cs b/src/Lucene.Net.Spatial/Query/SpatialArgs.cs
index 20030620b1..2927c9f48a 100644
--- a/src/Lucene.Net.Spatial/Query/SpatialArgs.cs
+++ b/src/Lucene.Net.Spatial/Query/SpatialArgs.cs
@@ -38,10 +38,9 @@ public class SpatialArgs
public SpatialArgs(SpatialOperation operation, IShape shape)
{
- if (operation == null || shape == null)
- throw new ArgumentException("operation and shape are required");
- this.Operation = operation;
- this.Shape = shape;
+ // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
+ this.Operation = operation ?? throw new ArgumentNullException(nameof(operation), "operation and shape are required");
+ this.Shape = shape ?? throw new ArgumentNullException(nameof(shape), "operation and shape are required");
}
///
@@ -55,9 +54,13 @@ public SpatialArgs(SpatialOperation operation, IShape shape)
/// A distance (in degrees).
public static double CalcDistanceFromErrPct(IShape shape, double distErrPct, SpatialContext ctx)
{
+ // LUCENENET: Added null guard clause
+ if (ctx is null)
+ throw new ArgumentNullException(nameof(ctx));
+
if (distErrPct < 0 || distErrPct > 0.5)
{
- throw new ArgumentException($"distErrPct {distErrPct} must be between [0 to 0.5]", nameof(distErrPct));
+ throw new ArgumentOutOfRangeException(nameof(distErrPct), $"distErrPct {distErrPct} must be between [0 to 0.5]", nameof(distErrPct));// LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (distErrPct == 0 || shape is IPoint)
{
diff --git a/src/Lucene.Net.Spatial/Query/SpatialArgsParser.cs b/src/Lucene.Net.Spatial/Query/SpatialArgsParser.cs
index 91758786db..5ea9ce5171 100644
--- a/src/Lucene.Net.Spatial/Query/SpatialArgsParser.cs
+++ b/src/Lucene.Net.Spatial/Query/SpatialArgsParser.cs
@@ -71,7 +71,7 @@ public static string WriteSpatialArgs(SpatialArgs args)
/// The spatial context. Mandatory.
/// Not null.
/// if the parameters don't make sense or an add-on parameter is unknown
- /// If there is a problem parsing the string
+ /// If there is a problem parsing the string
/// When the coordinates are invalid for the shape
public virtual SpatialArgs Parse(string v, SpatialContext ctx)
{
@@ -80,7 +80,7 @@ public virtual SpatialArgs Parse(string v, SpatialContext ctx)
if (idx < 0 || idx > edx)
{
- throw new ParseException("missing parens: " + v, -1);
+ throw new Spatial4n.Core.Exceptions.ParseException("missing parens: " + v, -1);
}
SpatialOperation op = SpatialOperation.Get(v.Substring(0, idx - 0).Trim());
@@ -90,7 +90,7 @@ public virtual SpatialArgs Parse(string v, SpatialContext ctx)
string body = v.Substring(idx + 1, edx - (idx + 1)).Trim();
if (body.Length < 1)
{
- throw new ParseException("missing body : " + v, idx + 1);
+ throw new Spatial4n.Core.Exceptions.ParseException("missing body : " + v, idx + 1);
}
var shape = ParseShape(body, ctx);
diff --git a/src/Lucene.Net.Spatial/Query/UnsupportedSpatialOperation.cs b/src/Lucene.Net.Spatial/Query/UnsupportedSpatialOperation.cs
index 04300c3747..d3952b1644 100644
--- a/src/Lucene.Net.Spatial/Query/UnsupportedSpatialOperation.cs
+++ b/src/Lucene.Net.Spatial/Query/UnsupportedSpatialOperation.cs
@@ -39,13 +39,13 @@ public UnsupportedSpatialOperation(SpatialOperation op)
{
}
-#if FEATURE_SERIALIZABLE_EXCEPTIONS
// For testing
- public UnsupportedSpatialOperation(string message)
+ internal UnsupportedSpatialOperation(string message)
: base(message)
{
}
+#if FEATURE_SERIALIZABLE_EXCEPTIONS
///
/// Initializes a new instance of this class with serialized data.
///
diff --git a/src/Lucene.Net.Spatial/Serialized/SerializedDVStrategy.cs b/src/Lucene.Net.Spatial/Serialized/SerializedDVStrategy.cs
index 485c752321..a172f7a5ec 100644
--- a/src/Lucene.Net.Spatial/Serialized/SerializedDVStrategy.cs
+++ b/src/Lucene.Net.Spatial/Serialized/SerializedDVStrategy.cs
@@ -69,9 +69,9 @@ public override Field[] CreateIndexableFields(IShape shape)
//this is a hack to avoid redundant byte array copying by byteStream.toByteArray()
byteStream.WriteTo(new OutputStreamAnonymousClass(bytesRef));
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
this.indexLastBufSize = bytesRef.Length;//cache heuristic
return new Field[] { new BinaryDocValuesField(FieldName, bytesRef) };
@@ -102,7 +102,7 @@ public override ValueSource MakeDistanceValueSource(IPoint queryPoint, double mu
public override ConstantScoreQuery MakeQuery(SpatialArgs args)
{
- throw new NotSupportedException("This strategy can't return a query that operates" +
+ throw UnsupportedOperationException.Create("This strategy can't return a query that operates" +
" efficiently. Instead try a Filter or ValueSource.");
}
@@ -162,7 +162,7 @@ public DocIdSetAnonymousClass(PredicateValueSourceFilter outerInstance, AtomicRe
public override DocIdSetIterator GetIterator()
{
- throw new NotSupportedException(
+ throw UnsupportedOperationException.Create(
"Iteration is too slow; instead try FilteredQuery.QUERY_FIRST_FILTER_STRATEGY");
//Note that if you're truly bent on doing this, then see FunctionValues.getRangeScorer
}
@@ -298,9 +298,9 @@ public override object ObjectVal(int docId)
{
return outerInstance.binaryCodec.ReadShape(dataInput);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
diff --git a/src/Lucene.Net.Spatial/SpatialStrategy.cs b/src/Lucene.Net.Spatial/SpatialStrategy.cs
index e2c4cd3d43..f0f6e3866e 100644
--- a/src/Lucene.Net.Spatial/SpatialStrategy.cs
+++ b/src/Lucene.Net.Spatial/SpatialStrategy.cs
@@ -59,9 +59,9 @@ public abstract class SpatialStrategy
///
protected SpatialStrategy(SpatialContext ctx, string fieldName)
{
- this.m_ctx = ctx ?? throw new ArgumentNullException(nameof(ctx), "ctx is required");
+ this.m_ctx = ctx ?? throw new ArgumentNullException(nameof(ctx), "ctx is required");// LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
if (string.IsNullOrEmpty(fieldName))
- throw new ArgumentException("fieldName is required", nameof(fieldName));
+ throw new ArgumentNullException(nameof(fieldName), "fieldName is required");// LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
this.fieldName = fieldName;
}
diff --git a/src/Lucene.Net.Spatial/Util/ValueSourceFilter.cs b/src/Lucene.Net.Spatial/Util/ValueSourceFilter.cs
index d8002d79ee..c3c3bb702f 100644
--- a/src/Lucene.Net.Spatial/Util/ValueSourceFilter.cs
+++ b/src/Lucene.Net.Spatial/Util/ValueSourceFilter.cs
@@ -42,6 +42,7 @@ public class ValueSourceFilter : Filter
public ValueSourceFilter(Filter startingFilter, ValueSource source, double min, double max)
{
+ // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
this.startingFilter = startingFilter ?? throw new ArgumentNullException(nameof(startingFilter),
"Please provide a non-null startingFilter; you can use QueryWrapperFilter(MatchAllDocsQuery) as a no-op filter");
this.source = source;
diff --git a/src/Lucene.Net.Spatial/Vector/PointVectorStrategy.cs b/src/Lucene.Net.Spatial/Vector/PointVectorStrategy.cs
index 7d42266c30..7a903b27c9 100644
--- a/src/Lucene.Net.Spatial/Vector/PointVectorStrategy.cs
+++ b/src/Lucene.Net.Spatial/Vector/PointVectorStrategy.cs
@@ -88,7 +88,7 @@ public override Field[] CreateIndexableFields(IShape shape)
if (shape is IPoint point)
return CreateIndexableFields(point);
- throw new NotSupportedException("Can only index IPoint, not " + shape);
+ throw UnsupportedOperationException.Create("Can only index IPoint, not " + shape);
}
///
@@ -150,7 +150,7 @@ public override ConstantScoreQuery MakeQuery(SpatialArgs args)
return new ConstantScoreQuery(vsf);
}
- throw new NotSupportedException("Only IRectangles and ICircles are currently supported, " +
+ throw UnsupportedOperationException.Create("Only IRectangles and ICircles are currently supported, " +
"found [" + shape.GetType().Name + "]"); //TODO
}
@@ -160,13 +160,13 @@ public virtual Query MakeQueryDistanceScore(SpatialArgs args)
// For starters, just limit the bbox
var shape = args.Shape;
if (!(shape is IRectangle || shape is ICircle))
- throw new NotSupportedException("Only Rectangles and Circles are currently supported, found ["
+ throw UnsupportedOperationException.Create("Only IRectangles and ICircles are currently supported, found ["
+ shape.GetType().Name + "]");//TODO
IRectangle bbox = shape.BoundingBox;
if (bbox.CrossesDateLine)
{
- throw new NotSupportedException("Crossing dateline not yet supported");
+ throw UnsupportedOperationException.Create("Crossing dateline not yet supported");
}
ValueSource valueSource = null;
@@ -261,7 +261,7 @@ private NumericRangeQuery RangeQuery(string fieldName, double? min, doub
private Query MakeDisjoint(IRectangle bbox)
{
if (bbox.CrossesDateLine)
- throw new NotSupportedException("MakeDisjoint doesn't handle dateline cross");
+ throw UnsupportedOperationException.Create("MakeDisjoint doesn't handle dateline cross");
Query qX = RangeQuery(fieldNameX, bbox.MinX, bbox.MaxX);
Query qY = RangeQuery(fieldNameY, bbox.MinY, bbox.MaxY);
diff --git a/src/Lucene.Net.Suggest/Spell/DirectSpellChecker.cs b/src/Lucene.Net.Suggest/Spell/DirectSpellChecker.cs
index 91e43326f2..3d2a5efa96 100644
--- a/src/Lucene.Net.Suggest/Spell/DirectSpellChecker.cs
+++ b/src/Lucene.Net.Suggest/Spell/DirectSpellChecker.cs
@@ -121,7 +121,7 @@ public virtual int MaxEdits
{
if (value < 1 || value > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE)
{
- throw new NotSupportedException("Invalid maxEdits");
+ throw UnsupportedOperationException.Create("Invalid maxEdits");
}
maxEdits = value;
}
diff --git a/src/Lucene.Net.Suggest/Spell/SpellChecker.cs b/src/Lucene.Net.Suggest/Spell/SpellChecker.cs
index 5e6f824b29..bbfc0ba500 100644
--- a/src/Lucene.Net.Suggest/Spell/SpellChecker.cs
+++ b/src/Lucene.Net.Suggest/Spell/SpellChecker.cs
@@ -655,7 +655,7 @@ private void EnsureOpen()
{
if (disposed)
{
- throw new ObjectDisposedException(this.GetType().FullName, "Spellchecker has been disposed.");
+ throw AlreadyClosedException.Create(this.GetType().FullName, "Spellchecker has been disposed.");
}
}
@@ -703,7 +703,7 @@ private void SwapSearcher(Directory dir)
if (disposed)
{
indexSearcher.IndexReader.Dispose();
- throw new ObjectDisposedException(this.GetType().FullName, "Spellchecker has been disposed.");
+ throw AlreadyClosedException.Create(this.GetType().FullName, "Spellchecker has been disposed.");
}
searcher?.IndexReader?.Dispose();
// set the spellindex in the sync block - ensure consistency.
diff --git a/src/Lucene.Net.Suggest/Spell/WordBreakSpellChecker.cs b/src/Lucene.Net.Suggest/Spell/WordBreakSpellChecker.cs
index 7130e7495e..a01631dd8d 100644
--- a/src/Lucene.Net.Suggest/Spell/WordBreakSpellChecker.cs
+++ b/src/Lucene.Net.Suggest/Spell/WordBreakSpellChecker.cs
@@ -487,11 +487,11 @@ internal SuggestWordArrayWrapper(SuggestWord[] suggestWords)
public int FreqSum => freqSum;
- // Required by the PriorityQueue's generic constraint, but we are using
+ // LUCENENET: Required by the PriorityQueue's generic constraint, but we are using
// IComparer here rather than IComparable
public int CompareTo(SuggestWordArrayWrapper other)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
@@ -510,11 +510,11 @@ internal CombineSuggestionWrapper(CombineSuggestion combineSuggestion, int numCo
public int NumCombinations => numCombinations;
- // Required by the PriorityQueue's generic constraint, but we are using
+ // LUCENENET: Required by the PriorityQueue's generic constraint, but we are using
// IComparer here rather than IComparable
public int CompareTo(CombineSuggestionWrapper other)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
}
diff --git a/src/Lucene.Net.Suggest/Suggest/Analyzing/AnalyzingInfixSuggester.cs b/src/Lucene.Net.Suggest/Suggest/Analyzing/AnalyzingInfixSuggester.cs
index ef411a74bf..6bb4748e29 100644
--- a/src/Lucene.Net.Suggest/Suggest/Analyzing/AnalyzingInfixSuggester.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Analyzing/AnalyzingInfixSuggester.cs
@@ -163,10 +163,9 @@ public AnalyzingInfixSuggester(LuceneVersion matchVersion, Directory dir, Analyz
public AnalyzingInfixSuggester(LuceneVersion matchVersion, Directory dir, Analyzer indexAnalyzer,
Analyzer queryAnalyzer, int minPrefixChars, bool commitOnBuild)
{
-
if (minPrefixChars < 0)
{
- throw new ArgumentException("minPrefixChars must be >= 0; got: " + minPrefixChars);
+ throw new ArgumentOutOfRangeException("minPrefixChars must be >= 0; got: " + minPrefixChars);// LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.m_queryAnalyzer = queryAnalyzer;
@@ -277,12 +276,12 @@ public override void Build(IInputEnumerator enumerator)
}
}
- //LUCENENET specific -Support for LUCENE - 5889.
+ // LUCENENET specific -Support for LUCENE-5889.
public void Commit()
{
if (writer == null)
{
- throw new InvalidOperationException("Cannot commit on an closed writer. Add documents first");
+ throw IllegalStateException.Create("Cannot commit on an closed writer. Add documents first");
}
writer.Commit();
}
@@ -407,9 +406,9 @@ private Document BuildDocument(BytesRef text, IEnumerable contexts, lo
///
public virtual void Refresh()
{
- if (m_searcherMgr == null)
+ if (m_searcherMgr == null) // LUCENENET specific -Support for LUCENE-5889.
{
- throw new InvalidOperationException("suggester was not built");
+ throw IllegalStateException.Create("suggester was not built");
}
m_searcherMgr.MaybeRefreshBlocking();
}
@@ -466,7 +465,7 @@ public virtual IList DoLookup(string key, IEnumerable co
if (m_searcherMgr == null)
{
- throw new InvalidOperationException("suggester was not built");
+ throw IllegalStateException.Create("suggester was not built");
}
Occur occur;
@@ -846,9 +845,9 @@ public override long GetSizeInBytes()
}
return mem;
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
- throw new Exception(ioe.ToString(), ioe);
+ throw RuntimeException.Create(ioe);
}
}
diff --git a/src/Lucene.Net.Suggest/Suggest/Analyzing/AnalyzingSuggester.cs b/src/Lucene.Net.Suggest/Suggest/Analyzing/AnalyzingSuggester.cs
index 01775fd06f..2f2e754e4c 100644
--- a/src/Lucene.Net.Suggest/Suggest/Analyzing/AnalyzingSuggester.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Analyzing/AnalyzingSuggester.cs
@@ -395,6 +395,10 @@ public int Compare(BytesRef a, BytesRef b)
public override void Build(IInputEnumerator enumerator)
{
+ // LUCENENET: Added guard clause for null
+ if (enumerator is null)
+ throw new ArgumentNullException(nameof(enumerator));
+
if (enumerator.HasContexts)
{
throw new ArgumentException("this suggester doesn't support contexts");
@@ -713,6 +717,10 @@ public override IList DoLookup(string key, IEnumerable c
{
if (Debugging.AssertsEnabled) Debugging.Assert(num > 0);
+ // LUCENENET: Added guard clause for null
+ if (key is null)
+ throw new ArgumentNullException(nameof(key));
+
if (onlyMorePopular)
{
throw new ArgumentException("this suggester only works with onlyMorePopular=false");
@@ -869,9 +877,9 @@ public override IList DoLookup(string key, IEnumerable c
return results;
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.ToString(), bogus);
+ throw RuntimeException.Create(bogus);
}
}
@@ -1015,7 +1023,7 @@ internal Automaton ToLookupAutomaton(string key)
///
public virtual object Get(string key)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
///
@@ -1031,7 +1039,7 @@ private static int EncodeWeight(long value)
{
if (value < 0 || value > int.MaxValue)
{
- throw new NotSupportedException("cannot encode value: " + value);
+ throw UnsupportedOperationException.Create("cannot encode value: " + value);
}
return int.MaxValue - (int)value;
}
diff --git a/src/Lucene.Net.Suggest/Suggest/Analyzing/FreeTextSuggester.cs b/src/Lucene.Net.Suggest/Suggest/Analyzing/FreeTextSuggester.cs
index 8f30e419fc..e5f5b35c83 100644
--- a/src/Lucene.Net.Suggest/Suggest/Analyzing/FreeTextSuggester.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Analyzing/FreeTextSuggester.cs
@@ -182,11 +182,11 @@ public FreeTextSuggester(Analyzer indexAnalyzer, Analyzer queryAnalyzer, int gra
this.queryAnalyzer = AddShingles(queryAnalyzer);
if (grams < 1)
{
- throw new ArgumentException("grams must be >= 1");
+ throw new ArgumentOutOfRangeException(nameof(grams), "grams must be >= 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if ((separator & 0x80) != 0)
{
- throw new ArgumentException("separator must be simple ascii character");
+ throw new ArgumentOutOfRangeException(nameof(separator), "separator must be simple ascii character"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.separator = separator;
}
@@ -299,6 +299,10 @@ public override void Build(IInputEnumerator enumerator)
///
public virtual void Build(IInputEnumerator enumerator, double ramBufferSizeMB)
{
+ // LUCENENET: Added guard clause for null
+ if (enumerator is null)
+ throw new ArgumentNullException(nameof(enumerator));
+
if (enumerator.HasPayloads)
{
throw new ArgumentException("this suggester doesn't support payloads");
@@ -361,7 +365,7 @@ public virtual void Build(IInputEnumerator enumerator, double ramBufferSizeMB)
reader = DirectoryReader.Open(writer, false);
Terms terms = MultiFields.GetTerms(reader, "body");
- if (terms == null)
+ if (terms is null)
{
throw new ArgumentException("need at least one suggestion");
}
@@ -390,7 +394,7 @@ public virtual void Build(IInputEnumerator enumerator, double ramBufferSizeMB)
}
fst = builder.Finish();
- if (fst == null)
+ if (fst is null)
{
throw new ArgumentException("need at least one suggestion");
}
@@ -434,7 +438,7 @@ public virtual void Build(IInputEnumerator enumerator, double ramBufferSizeMB)
}
catch (Exception e)
{
- throw new InvalidOperationException("failed to remove " + tempIndexPath, e);
+ throw IllegalStateException.Create("failed to remove " + tempIndexPath, e);
}
}
}
@@ -458,12 +462,12 @@ public override bool Load(DataInput input)
var separatorOrig = (sbyte)input.ReadByte();
if (separatorOrig != separator)
{
- throw new InvalidOperationException("separator=" + separator + " is incorrect: original model was built with separator=" + separatorOrig);
+ throw IllegalStateException.Create("separator=" + separator + " is incorrect: original model was built with separator=" + separatorOrig);
}
int gramsOrig = input.ReadVInt32();
if (gramsOrig != grams)
{
- throw new InvalidOperationException("grams=" + grams + " is incorrect: original model was built with grams=" + gramsOrig);
+ throw IllegalStateException.Create("grams=" + grams + " is incorrect: original model was built with grams=" + gramsOrig);
}
totTokens = input.ReadVInt64();
@@ -490,10 +494,10 @@ public override IList DoLookup(string key, IEnumerable c
{
return DoLookup(key, contexts, num);
}
- catch (IOException ioe)
+ catch (Exception ioe) when (ioe.IsIOException())
{
// bogus:
- throw new Exception(ioe.ToString(), ioe);
+ throw RuntimeException.Create(ioe);
}
}
@@ -518,12 +522,16 @@ private int CountGrams(BytesRef token)
///
public virtual IList DoLookup(string key, IEnumerable contexts, int num)
{
+ // LUCENENET: Added guard clause for null
+ if (key is null)
+ throw new ArgumentNullException(nameof(key));
+
if (contexts != null)
{
throw new ArgumentException("this suggester doesn't support contexts");
}
- TokenStream ts = queryAnalyzer.GetTokenStream("", key.ToString());
+ TokenStream ts = queryAnalyzer.GetTokenStream("", key);
try
{
ITermToBytesRefAttribute termBytesAtt = ts.AddAttribute();
@@ -646,9 +654,9 @@ public virtual IList DoLookup(string key, IEnumerable co
{
prefixOutput = LookupPrefix(fst, bytesReader, token, arc);
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.ToString(), bogus);
+ throw RuntimeException.Create(bogus);
}
//System.out.println(" prefixOutput=" + prefixOutput);
@@ -721,9 +729,9 @@ public virtual IList DoLookup(string key, IEnumerable co
completions = searcher.Search();
if (Debugging.AssertsEnabled) Debugging.Assert(completions.IsComplete);
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.ToString(), bogus);
+ throw RuntimeException.Create(bogus);
}
int prefixLength = token.Length;
@@ -905,7 +913,7 @@ private static long DecodeWeight(long? output)
///
public virtual object Get(string key)
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
}
\ No newline at end of file
diff --git a/src/Lucene.Net.Suggest/Suggest/Analyzing/FuzzySuggester.cs b/src/Lucene.Net.Suggest/Suggest/Analyzing/FuzzySuggester.cs
index 02e1ea5e64..229e20b725 100644
--- a/src/Lucene.Net.Suggest/Suggest/Analyzing/FuzzySuggester.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Analyzing/FuzzySuggester.cs
@@ -153,15 +153,15 @@ public FuzzySuggester(Analyzer indexAnalyzer, Analyzer queryAnalyzer, SuggesterO
{
if (maxEdits < 0 || maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE)
{
- throw new ArgumentException("maxEdits must be between 0 and " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
+ throw new ArgumentOutOfRangeException(nameof(maxEdits), "maxEdits must be between 0 and " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (nonFuzzyPrefix < 0)
{
- throw new ArgumentException("nonFuzzyPrefix must not be >= 0 (got " + nonFuzzyPrefix + ")");
+ throw new ArgumentOutOfRangeException(nameof(nonFuzzyPrefix), "nonFuzzyPrefix must not be >= 0 (got " + nonFuzzyPrefix + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (minFuzzyLength < 0)
{
- throw new ArgumentException("minFuzzyLength must not be >= 0 (got " + minFuzzyLength + ")");
+ throw new ArgumentOutOfRangeException(nameof(minFuzzyLength), "minFuzzyLength must not be >= 0 (got " + minFuzzyLength + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.maxEdits = maxEdits;
diff --git a/src/Lucene.Net.Suggest/Suggest/DocumentValueSourceDictionary.cs b/src/Lucene.Net.Suggest/Suggest/DocumentValueSourceDictionary.cs
index bcb53936c1..b8a5d3f00b 100644
--- a/src/Lucene.Net.Suggest/Suggest/DocumentValueSourceDictionary.cs
+++ b/src/Lucene.Net.Suggest/Suggest/DocumentValueSourceDictionary.cs
@@ -150,9 +150,9 @@ protected internal override long GetWeight(Document doc, int docId)
{
currentWeightValues = outerInstance.weightsValueSource.GetValues(new Dictionary(), leaves[currentLeafIndex]);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
return currentWeightValues.Int64Val(docId - starts[subIndex]);
diff --git a/src/Lucene.Net.Suggest/Suggest/FileDictionary.cs b/src/Lucene.Net.Suggest/Suggest/FileDictionary.cs
index d739016f59..ff1c363aa9 100644
--- a/src/Lucene.Net.Suggest/Suggest/FileDictionary.cs
+++ b/src/Lucene.Net.Suggest/Suggest/FileDictionary.cs
@@ -1,4 +1,5 @@
-using Lucene.Net.Search.Spell;
+using J2N.Text;
+using Lucene.Net.Search.Spell;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
@@ -118,9 +119,9 @@ public virtual IInputEnumerator GetEntryEnumerator()
{
return new FileEnumerator(this);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
@@ -248,17 +249,8 @@ internal void ReadWeight(string weight)
// LUCENENET specific - don't use exception, use TryParse
if (!long.TryParse(weight, NumberStyles.Integer, CultureInfo.InvariantCulture, out curWeight))
{
- try
- {
- // keep reading floats for bw compat
- curWeight = (long)double.Parse(weight, NumberStyles.Float, CultureInfo.InvariantCulture);
- }
- catch (FormatException e)
- {
- // LUCENENET TODO: This is just so we can see what string and what culture was being tested when parsing failed,
- // to try to reproduce the conditions of the failure.
- throw new FormatException($"Weight '{weight}' could not be parsed to long or double in culture '{CultureInfo.CurrentCulture.Name}'.", e);
- }
+ // keep reading floats for bw compat
+ curWeight = (long)double.Parse(weight, NumberStyles.Float, CultureInfo.InvariantCulture);
}
}
diff --git a/src/Lucene.Net.Suggest/Suggest/Fst/ExternalRefSorter.cs b/src/Lucene.Net.Suggest/Suggest/Fst/ExternalRefSorter.cs
index 95fa2f023a..40d6efb8fc 100644
--- a/src/Lucene.Net.Suggest/Suggest/Fst/ExternalRefSorter.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Fst/ExternalRefSorter.cs
@@ -47,7 +47,7 @@ public virtual void Add(BytesRef utf8)
{
if (writer == null)
{
- throw new InvalidOperationException();
+ throw IllegalStateException.Create();
}
writer.Write(utf8);
}
diff --git a/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletion.cs b/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletion.cs
index 441f8b05f1..bfd8dafa17 100644
--- a/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletion.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletion.cs
@@ -161,9 +161,9 @@ private static FST.Arc[] CacheRootArcs(FST automaton)
// we want highest weights first.
return rootArcs.ToArray();
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
@@ -204,10 +204,10 @@ private int GetExactMatchStartingFromRootArc(int rootArcIndex, BytesRef utf8)
}
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
// Should never happen, but anyway.
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
// No match.
@@ -225,7 +225,11 @@ private int GetExactMatchStartingFromRootArc(int rootArcIndex, BytesRef utf8)
/// (decreasing) and then alphabetically (UTF-8 codepoint order).
public virtual IList DoLookup(string key, int num)
{
- if (key.Length == 0 || automaton == null)
+ // LUCENENET: Added guard clause for null
+ if (key is null)
+ throw new ArgumentNullException(nameof(key));
+
+ if (key.Length == 0 || automaton is null)
{
return EMPTY_RESULT;
}
@@ -247,10 +251,10 @@ public virtual IList DoLookup(string key, int num)
return LookupSortedByWeight(keyUtf8, num, false);
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
// Should never happen, but anyway.
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
diff --git a/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletionBuilder.cs b/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletionBuilder.cs
index 93e9dba0ac..178f07b741 100644
--- a/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletionBuilder.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletionBuilder.cs
@@ -182,10 +182,10 @@ public FSTCompletionBuilder(int buckets, IBytesRefSorter sorter, int shareMaxTai
{
if (buckets < 1 || buckets > 255)
{
- throw new ArgumentOutOfRangeException(nameof(buckets), buckets, "Buckets must be >= 1 and <= 255");
+ throw new ArgumentOutOfRangeException(nameof(buckets), buckets, "Buckets must be >= 1 and <= 255"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
- this.sorter = sorter ?? throw new ArgumentNullException("BytesRefSorter must not be null.");
+ this.sorter = sorter ?? throw new ArgumentNullException(nameof(sorter), "BytesRefSorter must not be null."); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
this.buckets = buckets;
this.shareMaxTailLength = shareMaxTailLength;
}
@@ -203,9 +203,13 @@ public FSTCompletionBuilder(int buckets, IBytesRefSorter sorter, int shareMaxTai
/// before suggestions placed in smaller buckets.
public virtual void Add(BytesRef utf8, int bucket)
{
+ // LUCENENET: Added guard clause for null
+ if (utf8 is null)
+ throw new ArgumentNullException(nameof(utf8));
+
if (bucket < 0 || bucket >= buckets)
{
- throw new ArgumentException("Bucket outside of the allowed range [0, " + buckets + "): " + bucket);
+ throw new ArgumentOutOfRangeException(nameof(buckets), "Bucket outside of the allowed range [0, " + buckets + "): " + bucket); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (scratch.Bytes.Length < utf8.Length + 1)
diff --git a/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletionLookup.cs b/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletionLookup.cs
index bc2f877429..76c6727642 100644
--- a/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletionLookup.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletionLookup.cs
@@ -139,6 +139,10 @@ public FSTCompletionLookup(FSTCompletion completion, bool exactMatchFirst)
public override void Build(IInputEnumerator enumerator)
{
+ // LUCENENET: Added guard clause for null
+ if (enumerator is null)
+ throw new ArgumentNullException(nameof(enumerator));
+
if (enumerator.HasPayloads)
{
throw new ArgumentException("this suggester doesn't support payloads");
@@ -247,13 +251,17 @@ private static int EncodeWeight(long value)
{
if (value < int.MinValue || value > int.MaxValue)
{
- throw new NotSupportedException("cannot encode value: " + value);
+ throw UnsupportedOperationException.Create("cannot encode value: " + value);
}
return (int)value;
}
public override IList DoLookup(string key, IEnumerable contexts, bool higherWeightsFirst, int num)
{
+ // LUCENENET: Added guard clause for null
+ if (key is null)
+ throw new ArgumentNullException(nameof(key));
+
if (contexts != null)
{
throw new ArgumentException("this suggester doesn't support contexts");
diff --git a/src/Lucene.Net.Suggest/Suggest/Fst/WFSTCompletionLookup.cs b/src/Lucene.Net.Suggest/Suggest/Fst/WFSTCompletionLookup.cs
index add314c40c..20bfd19b84 100644
--- a/src/Lucene.Net.Suggest/Suggest/Fst/WFSTCompletionLookup.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Fst/WFSTCompletionLookup.cs
@@ -80,6 +80,10 @@ public WFSTCompletionLookup(bool exactFirst)
public override void Build(IInputEnumerator enumerator)
{
+ // LUCENENET: Added guard clause for null
+ if (enumerator is null)
+ throw new ArgumentNullException(nameof(enumerator));
+
if (enumerator.HasPayloads)
{
throw new ArgumentException("this suggester doesn't support payloads");
@@ -137,6 +141,9 @@ public override bool Load(DataInput input)
public override IList DoLookup(string key, IEnumerable contexts, bool onlyMorePopular, int num)
{
+ // LUCENENET: Added guard clause for null
+ if (key is null)
+ throw new ArgumentNullException(nameof(key));
if (contexts != null)
{
throw new ArgumentException("this suggester doesn't support contexts");
@@ -163,9 +170,9 @@ public override IList DoLookup(string key, IEnumerable c
{
prefixOutput = LookupPrefix(scratch, arc);
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.ToString(), bogus);
+ throw RuntimeException.Create(bogus);
}
if (!prefixOutput.HasValue)
@@ -193,9 +200,9 @@ public override IList DoLookup(string key, IEnumerable c
completions = Lucene.Net.Util.Fst.Util.ShortestPaths(fst, arc, prefixOutput, weightComparer, num, !exactFirst);
if (Debugging.AssertsEnabled) Debugging.Assert(completions.IsComplete);
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.ToString(), bogus);
+ throw RuntimeException.Create(bogus);
}
BytesRef suffix = new BytesRef(8);
@@ -254,9 +261,9 @@ public virtual object Get(string key)
{
result = LookupPrefix(new BytesRef(key), arc);
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.ToString(), bogus);
+ throw RuntimeException.Create(bogus);
}
if (!result.HasValue || !arc.IsFinal)
{
@@ -281,7 +288,7 @@ private static int EncodeWeight(long value)
{
if (value < 0 || value > int.MaxValue)
{
- throw new NotSupportedException("cannot encode value: " + value);
+ throw UnsupportedOperationException.Create("cannot encode value: " + value);
}
return int.MaxValue - (int)value;
}
diff --git a/src/Lucene.Net.Suggest/Suggest/InMemorySorter.cs b/src/Lucene.Net.Suggest/Suggest/InMemorySorter.cs
index ee4e2385ed..8cf4a0ff08 100644
--- a/src/Lucene.Net.Suggest/Suggest/InMemorySorter.cs
+++ b/src/Lucene.Net.Suggest/Suggest/InMemorySorter.cs
@@ -46,7 +46,7 @@ public void Add(BytesRef utf8)
{
if (closed)
{
- throw new InvalidOperationException();
+ throw IllegalStateException.Create();
}
buffer.Append(utf8);
}
diff --git a/src/Lucene.Net.Suggest/Suggest/Jaspell/JaspellLookup.cs b/src/Lucene.Net.Suggest/Suggest/Jaspell/JaspellLookup.cs
index d3396d5946..4cbb763f46 100644
--- a/src/Lucene.Net.Suggest/Suggest/Jaspell/JaspellLookup.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Jaspell/JaspellLookup.cs
@@ -47,6 +47,10 @@ public JaspellLookup()
public override void Build(IInputEnumerator enumerator)
{
+ // LUCENENET: Added guard clause for null
+ if (enumerator is null)
+ throw new ArgumentNullException(nameof(enumerator));
+
if (enumerator.HasPayloads)
{
throw new ArgumentException("this suggester doesn't support payloads");
diff --git a/src/Lucene.Net.Suggest/Suggest/Jaspell/JaspellTernarySearchTrie.cs b/src/Lucene.Net.Suggest/Suggest/Jaspell/JaspellTernarySearchTrie.cs
index 397c881c95..68b64606f2 100644
--- a/src/Lucene.Net.Suggest/Suggest/Jaspell/JaspellTernarySearchTrie.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Jaspell/JaspellTernarySearchTrie.cs
@@ -195,7 +195,7 @@ public JaspellTernarySearchTrie()
///
public JaspellTernarySearchTrie(CultureInfo culture)
{
- this.culture = culture ?? throw new ArgumentNullException(nameof(culture));
+ this.culture = culture ?? throw new ArgumentNullException(nameof(culture)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
// for loading
@@ -606,15 +606,15 @@ protected internal virtual TSTNode GetNode(string key, TSTNode startNode)
/// A that indexes the node that is returned.
/// The node object indexed by key. This object is an instance of an
/// inner class named .
- ///
+ ///
/// If the key is null.
///
/// If the key is an empty .
protected internal virtual TSTNode GetOrCreateNode(string key)
{
- if (key == null)
+ if (key is null)
{
- throw new NullReferenceException("attempt to get or create node with null key");
+ throw new ArgumentNullException(nameof(key), "attempt to get or create node with null key"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
}
if (key.Length == 0)
{
diff --git a/src/Lucene.Net.Suggest/Suggest/Tst/TSTLookup.cs b/src/Lucene.Net.Suggest/Suggest/Tst/TSTLookup.cs
index ea408525ee..887f627aa5 100644
--- a/src/Lucene.Net.Suggest/Suggest/Tst/TSTLookup.cs
+++ b/src/Lucene.Net.Suggest/Suggest/Tst/TSTLookup.cs
@@ -46,6 +46,10 @@ public TSTLookup()
public override void Build(IInputEnumerator enumerator)
{
+ // LUCENENT: Added guard clause for null
+ if (enumerator is null)
+ throw new ArgumentNullException(nameof(enumerator));
+
if (enumerator.HasPayloads)
{
throw new ArgumentException("this suggester doesn't support payloads");
diff --git a/src/Lucene.Net.TestFramework.NUnit/Support/TestFramework/Assert.cs b/src/Lucene.Net.TestFramework.NUnit/Support/TestFramework/Assert.cs
index fe891bc358..85aae2c167 100644
--- a/src/Lucene.Net.TestFramework.NUnit/Support/TestFramework/Assert.cs
+++ b/src/Lucene.Net.TestFramework.NUnit/Support/TestFramework/Assert.cs
@@ -3,6 +3,7 @@
using Lucene.Net.Support.IO;
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using _NUnit = NUnit.Framework;
@@ -55,6 +56,7 @@ protected Assert()
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(T expected, T actual)
{
@@ -80,6 +82,7 @@ public static void AreEqual(T expected, T actual)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(T expected, T actual, string message, params object[] args)
{
@@ -100,6 +103,7 @@ public static void AreEqual(T expected, T actual, string message, params obje
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(string expected, string actual)
{
@@ -123,6 +127,7 @@ public static void AreEqual(string expected, string actual)
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(string expected, string actual, string message, params object[] args)
{
@@ -143,6 +148,7 @@ public static void AreEqual(string expected, string actual, string message, para
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(bool expected, bool actual)
{
@@ -168,6 +174,7 @@ public static void AreEqual(bool expected, bool actual)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(bool expected, bool actual, string message, params object[] args)
{
@@ -196,6 +203,7 @@ public static void AreEqual(bool expected, bool actual, string message, params o
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(double expected, double actual, double delta, string message, params object[] args)
{
@@ -217,6 +225,7 @@ public static void AreEqual(double expected, double actual, double delta, string
//
// delta:
// The maximum acceptable difference between the the expected and the actual
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(double expected, double actual, double delta)
{
@@ -244,6 +253,7 @@ public static void AreEqual(double expected, double actual, double delta)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(float expected, float actual, float delta, string message, params object[] args)
{
@@ -265,6 +275,7 @@ public static void AreEqual(float expected, float actual, float delta, string me
//
// delta:
// The maximum acceptable difference between the the expected and the actual
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(float expected, float actual, float delta)
{
@@ -284,6 +295,7 @@ public static void AreEqual(float expected, float actual, float delta)
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(int expected, int actual)
{
@@ -307,6 +319,7 @@ public static void AreEqual(int expected, int actual)
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(int expected, int actual, string message, params object[] args)
{
@@ -327,6 +340,7 @@ public static void AreEqual(int expected, int actual, string message, params obj
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(long expected, long actual)
{
@@ -350,6 +364,7 @@ public static void AreEqual(long expected, long actual)
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(long expected, long actual, string message, params object[] args)
{
@@ -370,6 +385,7 @@ public static void AreEqual(long expected, long actual, string message, params o
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(byte expected, byte actual)
{
@@ -393,6 +409,7 @@ public static void AreEqual(byte expected, byte actual)
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(byte expected, byte actual, string message, params object[] args)
{
@@ -401,6 +418,7 @@ public static void AreEqual(byte expected, byte actual, string message, params o
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static JCG.SetEqualityComparer GetSetComparer(bool aggressive)
{
@@ -409,6 +427,7 @@ private static JCG.SetEqualityComparer GetSetComparer(bool aggressive)
: JCG.SetEqualityComparer.Default;
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static JCG.ListEqualityComparer GetListComparer(bool aggressive)
{
@@ -417,6 +436,7 @@ private static JCG.ListEqualityComparer GetListComparer(bool aggressive)
: JCG.ListEqualityComparer.Default;
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static JCG.DictionaryEqualityComparer GetDictionaryComparer(bool aggressive)
{
@@ -438,6 +458,7 @@ public static string FormatCollection(object collection)
return string.Format(StringFormatter.CurrentCulture, "{0}", collection);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(ISet expected, ISet actual, bool aggressive = true)
{
@@ -445,6 +466,7 @@ public static void AreEqual(ISet expected, ISet actual, bool aggressive
Fail(FailureFormat, FormatCollection(expected), FormatCollection(actual));
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(ISet expected, ISet actual, bool aggressive, string message, params object[] args)
{
@@ -453,6 +475,7 @@ public static void AreEqual(ISet expected, ISet actual, bool aggressive
Fail(FormatErrorMessage(FormatCollection(expected), FormatCollection(actual), message, args));
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(ISet expected, ISet actual, bool aggressive, Func getMessage)
{
@@ -460,6 +483,7 @@ public static void AreEqual(ISet expected, ISet actual, bool aggressive
Fail(FormatErrorMessage(FormatCollection(expected), FormatCollection(actual), getMessage()));
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(IList expected, IList actual, bool aggressive = true)
{
@@ -467,6 +491,7 @@ public static void AreEqual(IList expected, IList actual, bool aggressi
Fail(string.Format(FailureFormat, FormatCollection(expected), FormatCollection(actual)));
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(IList expected, IList actual, bool aggressive, string message, params object[] args)
{
@@ -474,6 +499,7 @@ public static void AreEqual(IList expected, IList actual, bool aggressi
Fail(FormatErrorMessage(FormatCollection(expected), FormatCollection(actual), message, args));
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(IList expected, IList actual, bool aggressive, Func getMessage)
{
@@ -481,6 +507,7 @@ public static void AreEqual(IList expected, IList actual, bool aggressi
Fail(FormatErrorMessage(FormatCollection(expected), FormatCollection(actual), getMessage()));
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(IDictionary expected, IDictionary actual, bool aggressive = true)
{
@@ -488,6 +515,7 @@ public static void AreEqual(IDictionary expected, ID
Fail(FailureFormat, FormatCollection(expected), FormatCollection(actual));
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(IDictionary expected, IDictionary actual, bool aggressive, string message, params object[] args)
{
@@ -495,6 +523,7 @@ public static void AreEqual(IDictionary expected, ID
Fail(FormatErrorMessage(FormatCollection(expected), FormatCollection(actual), message, args));
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(IDictionary expected, IDictionary actual, bool aggressive, Func getMessage)
{
@@ -504,6 +533,7 @@ public static void AreEqual(IDictionary expected, ID
// From CollectionAssert
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(T[] expected, T[] actual)
{
@@ -512,6 +542,7 @@ public static void AreEqual(T[] expected, T[] actual)
}
// From CollectionAssert
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(T[] expected, T[] actual, string message, params object[] args)
{
@@ -520,6 +551,7 @@ public static void AreEqual(T[] expected, T[] actual, string message, params
}
// From CollectionAssert
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual(T[] expected, T[] actual, Func getMessage)
{
@@ -546,6 +578,7 @@ public static void AreEqual(T[] expected, T[] actual, Func getMessage
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreNotEqual(object expected, object actual, string message, params object[] args)
{
@@ -564,6 +597,7 @@ public static void AreNotEqual(object expected, object actual, string message, p
//
// actual:
// The actual value
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreNotEqual(object expected, object actual)
{
@@ -586,6 +620,7 @@ public static void AreNotEqual(object expected, object actual)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreNotSame(object expected, object actual, string message, params object[] args)
{
@@ -602,6 +637,7 @@ public static void AreNotSame(object expected, object actual, string message, pa
//
// actual:
// The actual object
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreNotSame(object expected, object actual)
{
@@ -618,6 +654,7 @@ public static void AreNotSame(object expected, object actual)
//
// actual:
// The actual object
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreSame(object expected, object actual)
{
@@ -640,12 +677,14 @@ public static void AreSame(object expected, object actual)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreSame(object expected, object actual, string message, params object[] args)
{
_NUnit.Assert.AreSame(expected, actual, message, args);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Fail(string message, params object[] args)
{
@@ -655,6 +694,7 @@ public static void Fail(string message, params object[] args)
// Summary:
// Throws an NUnit.Framework.AssertionException. This is used by the other Assert
// functions.
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Fail()
{
@@ -668,12 +708,34 @@ public static void Fail()
// Parameters:
// message:
// The message to initialize the NUnit.Framework.AssertionException with.
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Fail(string message)
{
_NUnit.Assert.Fail(message);
}
+ [DebuggerStepThrough]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void Pass(string message, params object[] args)
+ {
+ _NUnit.Assert.Pass(message, args);
+ }
+
+ [DebuggerStepThrough]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void Pass(string message)
+ {
+ _NUnit.Assert.Pass(message);
+ }
+
+ [DebuggerStepThrough]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void Pass()
+ {
+ _NUnit.Assert.Pass();
+ }
+
//
// Summary:
// Asserts that a condition is false. If the condition is true the method throws
@@ -688,6 +750,7 @@ public static void Fail(string message)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void False(bool condition, string message, params object[] args)
{
@@ -702,6 +765,7 @@ public static void False(bool condition, string message, params object[] args)
// Parameters:
// condition:
// The evaluated condition
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void False(bool condition)
{
@@ -717,6 +781,7 @@ public static void False(bool condition)
// Parameters:
// condition:
// The evaluated condition
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsFalse(bool condition)
{
@@ -738,6 +803,7 @@ public static void IsFalse(bool condition)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsFalse(bool condition, string message, params object[] args)
{
@@ -759,6 +825,7 @@ public static void IsFalse(bool condition, string message, params object[] args)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsNotNull(object anObject, string message, params object[] args)
{
@@ -772,6 +839,7 @@ public static void IsNotNull(object anObject, string message, params object[] ar
// Parameters:
// anObject:
// The object that is to be tested
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsNotNull(object anObject)
{
@@ -785,6 +853,7 @@ public static void IsNotNull(object anObject)
// Parameters:
// anObject:
// The object that is to be tested
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsNull(object anObject)
{
@@ -804,6 +873,7 @@ public static void IsNull(object anObject)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsNull(object anObject, string message, params object[] args)
{
@@ -824,6 +894,7 @@ public static void IsNull(object anObject, string message, params object[] args)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsTrue(bool condition, string message, params object[] args)
{
@@ -839,6 +910,7 @@ public static void IsTrue(bool condition, string message, params object[] args)
// Parameters:
// condition:
// The evaluated condition
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsTrue(bool condition)
{
@@ -854,6 +926,7 @@ public static void IsTrue(bool condition)
// Parameters:
// anObject:
// The object that is to be tested
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NotNull(object anObject)
{
@@ -874,6 +947,7 @@ public static void NotNull(object anObject)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NotNull(object anObject, string message, params object[] args)
{
@@ -895,6 +969,7 @@ public static void NotNull(object anObject, string message, params object[] args
//
// args:void Null
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Null(object anObject, string message, params object[] args)
{
@@ -909,6 +984,7 @@ public static void Null(object anObject, string message, params object[] args)
// Parameters:
// anObject:
// The object that is to be tested
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Null(object anObject)
{
@@ -930,6 +1006,7 @@ public static void Null(object anObject)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void True(bool condition, string message, params object[] args)
{
@@ -945,6 +1022,7 @@ public static void True(bool condition, string message, params object[] args)
// Parameters:
// condition:
// The evaluated condition
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void True(bool condition)
{
@@ -967,6 +1045,7 @@ public static void True(bool condition)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsNotEmpty(string aString, string message, params object[] args)
{
@@ -981,6 +1060,7 @@ public static void IsNotEmpty(string aString, string message, params object[] ar
// Parameters:
// anObject:
// The object that is to be tested
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsNotEmpty(string aString)
{
@@ -1003,6 +1083,7 @@ public static void IsNotEmpty(string aString)
//
// args:
// Array of objects to be used in formatting the message
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsEmpty(string aString, string message, params object[] args)
{
@@ -1017,6 +1098,7 @@ public static void IsEmpty(string aString, string message, params object[] args)
// Parameters:
// anObject:
// The object that is to be tested
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsEmpty(string aString)
{
@@ -1024,6 +1106,7 @@ public static void IsEmpty(string aString)
_NUnit.Assert.IsEmpty(aString);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void LessOrEqual(int arg1, int arg2)
{
@@ -1031,6 +1114,7 @@ public static void LessOrEqual(int arg1, int arg2)
_NUnit.Assert.LessOrEqual(arg1, arg2);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Greater(int arg1, int arg2)
{
@@ -1038,42 +1122,49 @@ public static void Greater(int arg1, int arg2)
_NUnit.Assert.Greater(arg1, arg2);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DoesNotThrow(Action action, string message, params object[] args)
{
_NUnit.Assert.DoesNotThrow(() => action(), message, args);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DoesNotThrow(Action action)
{
_NUnit.Assert.DoesNotThrow(() => action());
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Exception Throws(Action action, string message, params object[] args)
{
return Throws(typeof(TException), action, message, args);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Exception Throws(Action action)
{
return Throws(typeof(TException), action);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Exception Throws(Type expectedExceptionType, Action action)
{
return _NUnit.Assert.Throws(expectedExceptionType, () => action());
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Exception Throws(Type expectedExceptionType, Action action, string message, params object[] args)
{
return _NUnit.Assert.Throws(expectedExceptionType, () => action(), message, args);
}
+ [DebuggerStepThrough]
public static Exception ThrowsFileAlreadyExistsException(string filePath, Action action)
{
var messagePrefix = $"Expected: IOException indicating file not found\nBut was:";
@@ -1092,18 +1183,21 @@ public static Exception ThrowsFileAlreadyExistsException(string filePath, Action
}
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Exception ThrowsAnyOf(Action action)
{
return ThrowsAnyOf(new Type[] { typeof(TException1), typeof(TException2) }, action);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Exception ThrowsAnyOf(Action action)
{
return ThrowsAnyOf(new Type[] { typeof(TException1), typeof(TException2), typeof(TException3) }, action);
}
+ [DebuggerStepThrough]
public static Exception ThrowsAnyOf(IEnumerable expectedExceptionTypes, Action action)
{
Exception exception = null;
diff --git a/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs b/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs
index 0b070ffbd6..b26c20a424 100644
--- a/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs
@@ -13,7 +13,6 @@
using System.Text;
using System.Threading;
using Assert = Lucene.Net.TestFramework.Assert;
-using AssertionError = Lucene.Net.Diagnostics.AssertionException;
using Attribute = Lucene.Net.Util.Attribute;
using AttributeFactory = Lucene.Net.Util.AttributeSource.AttributeFactory;
using Console = Lucene.Net.Util.SystemConsole;
@@ -555,21 +554,18 @@ internal static void CheckResetException(Analyzer a, string input)
Assert.Fail("didn't get expected exception when reset() not called");
}
}
-#pragma warning disable 168
- catch (InvalidOperationException expected)
-#pragma warning restore 168
+ catch (Exception expected) when (expected.IsIllegalStateException())
{
//ok
}
- catch (AssertionError expected) // LUCENENET: Actual AssertionError type is Lucene.Net.Diagnostics.AssertionException
+ catch (Exception expected) when (expected.IsAssertionError())
{
// ok: MockTokenizer
Assert.IsTrue(expected.Message != null && expected.Message.Contains("wrong state"), expected.Message);
}
- catch (Exception unexpected)
+ catch (Exception unexpected) when (unexpected.IsException())
{
- //unexpected.printStackTrace(System.err);
- Console.Error.WriteLine(unexpected.StackTrace);
+ unexpected.printStackTrace(Console.Error);
Assert.Fail("Got wrong exception when Reset() not called: " + unexpected);
}
finally
@@ -595,7 +591,7 @@ internal static void CheckResetException(Analyzer a, string input)
ts = a.GetTokenStream("bogus", new StringReader(input));
Assert.Fail("Didn't get expected exception when Dispose() not called");
}
- catch (Exception)
+ catch (Exception expected) when (expected.IsIllegalStateException())
{
// ok
}
@@ -720,7 +716,7 @@ public override void Run()
CheckRandomData(new Random((int)seed), a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw);
success = true;
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException()) // LUCENENET TODO: This catch block can be removed because Rethrow.rethrow() simply does what its name says, but need to get rid of the FirstException functionality and fix ThreadJob so it re-throws ThreadInterruptedExcepetion first.
{
//Console.WriteLine("Exception in Thread: " + e);
//throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
@@ -800,7 +796,7 @@ public void CheckRandomData(Random random, Analyzer a, int iterations, int maxWo
{
t.Join();
}
- catch (ThreadInterruptedException)
+ catch (Exception e) when (e.IsInterruptedException())
{
fail("Thread interrupted");
}
@@ -946,9 +942,7 @@ private static void CheckRandomData(Random random, Analyzer a, int iterations, i
}
}
}
-#pragma warning disable 168
- catch (Exception t)
-#pragma warning restore 168
+ catch (Exception t) when (t.IsThrowable())
{
// TODO: really we should pass a random seed to
// checkAnalysisConsistency then print it here too:
@@ -1141,7 +1135,7 @@ private static void CheckAnalysisConsistency(Random random, Analyzer a, bool use
while (ts.IncrementToken()) ;
Assert.Fail("did not hit exception");
}
- catch (Exception re)
+ catch (Exception re) when (re.IsRuntimeException())
{
Assert.IsTrue(MockReaderWrapper.IsMyEvilException(re));
}
@@ -1150,8 +1144,7 @@ private static void CheckAnalysisConsistency(Random random, Analyzer a, bool use
{
ts.End();
}
- // LUCENENET: Actual AssertionError type is Lucene.Net.Diagnostics.AssertionException
- catch (AssertionError ae) when (ae.Message.Contains("End() called before IncrementToken() returned false!"))
+ catch (Exception ae) when (ae.IsAssertionError() && ae.Message.Contains("End() called before IncrementToken() returned false!"))
{
// Catch & ignore MockTokenizer's
// anger...
@@ -1183,8 +1176,7 @@ private static void CheckAnalysisConsistency(Random random, Analyzer a, bool use
{
ts.End();
}
- // LUCENENET: Actual AssertionError type is Lucene.Net.Diagnostics.AssertionException
- catch (AssertionError ae) when (ae.Message.Contains("End() called before IncrementToken() returned false!"))
+ catch (Exception ae) when (ae.IsAssertionError() && ae.Message.Contains("End() called before IncrementToken() returned false!"))
{
// Catch & ignore MockTokenizer's
// anger...
@@ -1310,7 +1302,7 @@ public static AttributeFactory NewAttributeFactory(Random random)
case 1:
return AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY;
default:
- throw new AssertionError("Please fix the Random.nextInt() call above");
+ throw AssertionError.Create("Please fix the Random.nextInt() call above");
}
//switch (random.nextInt(3))
@@ -1322,7 +1314,7 @@ public static AttributeFactory NewAttributeFactory(Random random)
// case 2:
// return AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY;
// default:
- // throw new AssertionError("Please fix the Random.nextInt() call above");
+ // throw AssertionError.Create("Please fix the Random.nextInt() call above");
//}
}
diff --git a/src/Lucene.Net.TestFramework/Analysis/CannedBinaryTokenStream.cs b/src/Lucene.Net.TestFramework/Analysis/CannedBinaryTokenStream.cs
index cf88f694ca..430478b6b3 100644
--- a/src/Lucene.Net.TestFramework/Analysis/CannedBinaryTokenStream.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/CannedBinaryTokenStream.cs
@@ -98,7 +98,7 @@ public override void CopyTo(IAttribute target)
public override object Clone()
{
- throw new NotSupportedException();
+ throw UnsupportedOperationException.Create();
}
}
diff --git a/src/Lucene.Net.TestFramework/Analysis/CollationTestBase.cs b/src/Lucene.Net.TestFramework/Analysis/CollationTestBase.cs
index f3a373bd7f..f3810d906d 100644
--- a/src/Lucene.Net.TestFramework/Analysis/CollationTestBase.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/CollationTestBase.cs
@@ -261,7 +261,7 @@ public virtual void AssertThreadSafe(Analyzer analyzer)
for (int i = 0; i < numTestPoints; i++)
{
string term = TestUtil.RandomSimpleString(Random);
- IOException priorException = null;
+ Exception priorException = null; // LUCENENET: No need to cast to IOExcpetion
TokenStream ts = analyzer.GetTokenStream("fake", new StringReader(term));
try
{
@@ -275,7 +275,7 @@ public virtual void AssertThreadSafe(Analyzer analyzer)
Assert.IsFalse(ts.IncrementToken());
ts.End();
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
priorException = e;
}
@@ -319,7 +319,7 @@ public override void Run()
{
string term = mapping.Key;
BytesRef expected = mapping.Value;
- IOException priorException = null;
+ Exception priorException = null; // LUCENENET: No need to cast to IOExcpetion
TokenStream ts = this.analyzer.GetTokenStream("fake", new StringReader(term));
try
{
@@ -332,7 +332,7 @@ public override void Run()
Assert.IsFalse(ts.IncrementToken());
ts.End();
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
priorException = e;
}
@@ -342,9 +342,9 @@ public override void Run()
}
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
}
diff --git a/src/Lucene.Net.TestFramework/Analysis/MockCharFilter.cs b/src/Lucene.Net.TestFramework/Analysis/MockCharFilter.cs
index af1be4246a..442ff02053 100644
--- a/src/Lucene.Net.TestFramework/Analysis/MockCharFilter.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/MockCharFilter.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Diagnostics;
+using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.IO;
@@ -40,7 +40,7 @@ public MockCharFilter(TextReader @in, int remainder)
this.remainder = remainder;
if (remainder < 0 || remainder >= 10)
{
- throw new ArgumentException("invalid remainder parameter (must be 0..10): " + remainder);
+ throw new ArgumentOutOfRangeException(nameof(remainder), "invalid remainder parameter (must be 0..10): " + remainder); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
}
diff --git a/src/Lucene.Net.TestFramework/Analysis/MockFixedLengthPayloadFilter.cs b/src/Lucene.Net.TestFramework/Analysis/MockFixedLengthPayloadFilter.cs
index ad6a31780e..202f066205 100644
--- a/src/Lucene.Net.TestFramework/Analysis/MockFixedLengthPayloadFilter.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/MockFixedLengthPayloadFilter.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Analysis.TokenAttributes;
+using Lucene.Net.Analysis.TokenAttributes;
using System;
namespace Lucene.Net.Analysis
@@ -37,7 +37,7 @@ public MockFixedLengthPayloadFilter(Random random, TokenStream @in, int length)
{
if (length < 0)
{
- throw new ArgumentException("length must be >= 0");
+ throw new ArgumentOutOfRangeException(nameof(length), "length must be >= 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.random = random;
this.bytes = new byte[length];
diff --git a/src/Lucene.Net.TestFramework/Analysis/MockGraphTokenFilter.cs b/src/Lucene.Net.TestFramework/Analysis/MockGraphTokenFilter.cs
index dce9b04cb3..c248a72a5b 100644
--- a/src/Lucene.Net.TestFramework/Analysis/MockGraphTokenFilter.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/MockGraphTokenFilter.cs
@@ -1,7 +1,6 @@
-using Lucene.Net.Analysis.TokenAttributes;
+using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;
using System;
-using AssertionError = Lucene.Net.Diagnostics.AssertionException;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Analysis
@@ -132,7 +131,7 @@ public override bool IncrementToken()
}
if (random == null)
{
- throw new AssertionError("IncrementToken() called in wrong state!");
+ throw IllegalStateException.Create("IncrementToken() called in wrong state!");
}
return NextToken();
}
diff --git a/src/Lucene.Net.TestFramework/Analysis/MockReaderWrapper.cs b/src/Lucene.Net.TestFramework/Analysis/MockReaderWrapper.cs
index f7527ca8be..2b140989d9 100644
--- a/src/Lucene.Net.TestFramework/Analysis/MockReaderWrapper.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/MockReaderWrapper.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Diagnostics;
+using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
using System;
using System.IO;
@@ -113,7 +113,7 @@ private void ThrowExceptionIfApplicable()
{
if (throwExcNext || (excAtChar != -1 && readSoFar >= excAtChar))
{
- throw new Exception("fake exception now!");
+ throw RuntimeException.Create("fake exception now!");
}
}
diff --git a/src/Lucene.Net.TestFramework/Analysis/ValidatingTokenFilter.cs b/src/Lucene.Net.TestFramework/Analysis/ValidatingTokenFilter.cs
index 18f3ddef29..f7ff468a30 100644
--- a/src/Lucene.Net.TestFramework/Analysis/ValidatingTokenFilter.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/ValidatingTokenFilter.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Analysis.TokenAttributes;
+using Lucene.Net.Analysis.TokenAttributes;
using System;
using System.Collections.Generic;
@@ -97,7 +97,7 @@ public override bool IncrementToken()
pos += posIncAtt.PositionIncrement;
if (pos == -1)
{
- throw new Exception("first posInc must be > 0");
+ throw IllegalStateException.Create("first posInc must be > 0");
}
}
@@ -110,7 +110,7 @@ public override bool IncrementToken()
if (offsetsAreCorrect && offsetAtt.StartOffset < lastStartOffset)
{
- throw new Exception(name + ": offsets must not go backwards startOffset=" + startOffset + " is < lastStartOffset=" + lastStartOffset);
+ throw IllegalStateException.Create(name + ": offsets must not go backwards startOffset=" + startOffset + " is < lastStartOffset=" + lastStartOffset);
}
lastStartOffset = offsetAtt.StartOffset;
}
@@ -132,7 +132,7 @@ public override bool IncrementToken()
//System.out.println(" + vs " + pos + " -> " + startOffset);
if (oldStartOffset != startOffset)
{
- throw new Exception(name + ": inconsistent startOffset at pos=" + pos + ": " + oldStartOffset + " vs " + startOffset + "; token=" + termAtt);
+ throw IllegalStateException.Create(name + ": inconsistent startOffset at pos=" + pos + ": " + oldStartOffset + " vs " + startOffset + "; token=" + termAtt);
}
}
@@ -151,7 +151,7 @@ public override bool IncrementToken()
//System.out.println(" + ve " + endPos + " -> " + endOffset);
if (oldEndOffset != endOffset)
{
- throw new Exception(name + ": inconsistent endOffset at pos=" + endPos + ": " + oldEndOffset + " vs " + endOffset + "; token=" + termAtt);
+ throw IllegalStateException.Create(name + ": inconsistent endOffset at pos=" + endPos + ": " + oldEndOffset + " vs " + endOffset + "; token=" + termAtt);
}
}
}
diff --git a/src/Lucene.Net.TestFramework/Codecs/Asserting/AssertingDocValuesFormat.cs b/src/Lucene.Net.TestFramework/Codecs/Asserting/AssertingDocValuesFormat.cs
index 625865f41f..c27edc66d4 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Asserting/AssertingDocValuesFormat.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Asserting/AssertingDocValuesFormat.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Codecs.Lucene45;
+using Lucene.Net.Codecs.Lucene45;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Util;
@@ -217,17 +217,17 @@ protected override void Dispose(bool disposing)
public override void AddBinaryField(FieldInfo field, IEnumerable values)
{
- throw new InvalidOperationException();
+ throw IllegalStateException.Create();
}
public override void AddSortedField(FieldInfo field, IEnumerable values, IEnumerable docToOrd)
{
- throw new InvalidOperationException();
+ throw IllegalStateException.Create();
}
public override void AddSortedSetField(FieldInfo field, IEnumerable values, IEnumerable docToOrdCount, IEnumerable ords)
{
- throw new InvalidOperationException();
+ throw IllegalStateException.Create();
}
}
@@ -242,13 +242,13 @@ private static void CheckIterator(IEnumerator iterator, long expectedSize,
T v = iterator.Current;
if (Debugging.AssertsEnabled) Debugging.Assert(allowNull || v != null);
- // LUCENE.NET specific. removed call to Reset().
+ // LUCENENET specific - .NET doesn't support remove
//try
//{
- // iterator.Reset();
- // throw new InvalidOperationException("broken iterator (supports remove): " + iterator);
+ // iterator.remove();
+ // throw AssertionError.Create("broken iterator (supports remove): " + iterator);
//}
- //catch (NotSupportedException)
+ //catch (Exception expected) when (e.IsUnsupportedOperationException())
//{
// // ok
//}
@@ -257,7 +257,7 @@ private static void CheckIterator(IEnumerator iterator, long expectedSize,
/*try
{
//iterator.next();
- throw new InvalidOperationException("broken iterator (allows next() when hasNext==false) " + iterator);
+ throw AssertionError.Create("broken iterator (allows next() when hasNext==false) " + iterator);
}
catch (Exception)
{
diff --git a/src/Lucene.Net.TestFramework/Codecs/Compressing/CompressingCodec.cs b/src/Lucene.Net.TestFramework/Codecs/Compressing/CompressingCodec.cs
index 99ead48972..7b48156537 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Compressing/CompressingCodec.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Compressing/CompressingCodec.cs
@@ -1,5 +1,6 @@
using Lucene.Net.Codecs.Compressing.Dummy;
using Lucene.Net.Codecs.Lucene46;
+using Lucene.Net.Diagnostics;
using System;
using RandomInts = RandomizedTesting.Generators.RandomNumbers;
@@ -48,7 +49,7 @@ public static CompressingCodec RandomInstance(Random random, int chunkSize, bool
return new DummyCompressingCodec(chunkSize, withSegmentSuffix);
default:
- throw new InvalidOperationException();
+ throw AssertionError.Create();
}
}
diff --git a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWFieldsWriter.cs b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWFieldsWriter.cs
index b151b323c2..a9b243af74 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWFieldsWriter.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWFieldsWriter.cs
@@ -87,7 +87,7 @@ public override TermsConsumer AddField(FieldInfo field)
// LUCENENET specific - to avoid boxing, changed from CompareTo() to IndexOptionsComparer.Compare()
if (IndexOptionsComparer.Default.Compare(field.IndexOptions, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0)
{
- throw new NotSupportedException("this codec cannot index offsets");
+ throw UnsupportedOperationException.Create("this codec cannot index offsets");
}
//System.out.println("w field=" + field.Name + " storePayload=" + field.storePayloads + " number=" + field.number);
return new PreFlexTermsWriter(this, field);
diff --git a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWNormsConsumer.cs b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWNormsConsumer.cs
index 704e5c8f23..9b2497581f 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWNormsConsumer.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWNormsConsumer.cs
@@ -4,7 +4,6 @@
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
-using AssertionError = Lucene.Net.Diagnostics.AssertionException;
namespace Lucene.Net.Codecs.Lucene3x
{
@@ -82,7 +81,7 @@ public override void AddNumericField(FieldInfo field, IEnumerable values)
{
if (((sbyte)n) < sbyte.MinValue || ((sbyte)n) > sbyte.MaxValue)
{
- throw new NotSupportedException("3.x cannot index norms that won't fit in a byte, got: " + ((sbyte)n));
+ throw UnsupportedOperationException.Create("3.x cannot index norms that won't fit in a byte, got: " + ((sbyte)n));
}
@out.WriteByte((byte)n);
}
@@ -97,17 +96,17 @@ protected override void Dispose(bool disposing)
public override void AddBinaryField(FieldInfo field, IEnumerable values)
{
- throw new AssertionError();
+ throw AssertionError.Create();
}
public override void AddSortedField(FieldInfo field, IEnumerable values, IEnumerable docToOrd)
{
- throw new AssertionError();
+ throw AssertionError.Create();
}
public override void AddSortedSetField(FieldInfo field, IEnumerable values, IEnumerable docToOrdCount, IEnumerable ords)
{
- throw new AssertionError();
+ throw AssertionError.Create();
}
}
}
\ No newline at end of file
diff --git a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWStoredFieldsWriter.cs b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWStoredFieldsWriter.cs
index 567cb2f075..df851da3a9 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWStoredFieldsWriter.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWStoredFieldsWriter.cs
@@ -93,9 +93,8 @@ public override void Abort()
{
Dispose();
}
- catch (Exception)
+ catch (Exception ignored) when (ignored.IsThrowable())
{
- // ignored
}
IOUtils.DeleteFilesIgnoringExceptions(directory,
IndexFileNames.SegmentFileName(segment, "", Lucene3xStoredFieldsReader.FIELDS_EXTENSION),
@@ -204,7 +203,7 @@ public override void Finish(FieldInfos fis, int numDocs)
// entering the index. See LUCENE-1282 for
// details.
{
- throw new Exception("fdx size mismatch: docCount is " + numDocs + " but fdx file size is " + indexStream.GetFilePointer() + " file=" + indexStream.ToString() + "; now aborting this merge to prevent index corruption");
+ throw RuntimeException.Create("fdx size mismatch: docCount is " + numDocs + " but fdx file size is " + indexStream.GetFilePointer() + " file=" + indexStream.ToString() + "; now aborting this merge to prevent index corruption");
}
}
}
diff --git a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWTermVectorsWriter.cs b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWTermVectorsWriter.cs
index 0b53109946..9c3129efeb 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWTermVectorsWriter.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/PreFlexRWTermVectorsWriter.cs
@@ -1,4 +1,4 @@
-using J2N.Text;
+using J2N.Text;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Store;
@@ -81,7 +81,7 @@ public override void StartField(FieldInfo info, int numTerms, bool positions, bo
lastFieldName = info.Name;
if (payloads)
{
- throw new NotSupportedException("3.x codec does not support payloads on vectors!");
+ throw UnsupportedOperationException.Create("3.x codec does not support payloads on vectors!");
}
this.positions = positions;
this.offsets = offsets;
@@ -194,12 +194,12 @@ public override void Abort()
{
Dispose();
}
-#pragma warning disable 168, IDE0059
- catch (Exception ignored)
-#pragma warning restore 168, IDE0059
+ catch (Exception ignored) when (ignored.IsThrowable())
{
}
- IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, "", Lucene3xTermVectorsReader.VECTORS_INDEX_EXTENSION), IndexFileNames.SegmentFileName(segment, "", Lucene3xTermVectorsReader.VECTORS_DOCUMENTS_EXTENSION), IndexFileNames.SegmentFileName(segment, "", Lucene3xTermVectorsReader.VECTORS_FIELDS_EXTENSION));
+ IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, "", Lucene3xTermVectorsReader.VECTORS_INDEX_EXTENSION),
+ IndexFileNames.SegmentFileName(segment, "", Lucene3xTermVectorsReader.VECTORS_DOCUMENTS_EXTENSION),
+ IndexFileNames.SegmentFileName(segment, "", Lucene3xTermVectorsReader.VECTORS_FIELDS_EXTENSION));
}
public override void Finish(FieldInfos fis, int numDocs)
@@ -211,7 +211,7 @@ public override void Finish(FieldInfos fis, int numDocs)
// entering the index. See LUCENE-1282 for
// details.
{
- throw new Exception("tvx size mismatch: mergedDocs is " + numDocs + " but tvx size is " + tvx.GetFilePointer() + " file=" + tvx.ToString() + "; now aborting this merge to prevent index corruption");
+ throw RuntimeException.Create("tvx size mismatch: mergedDocs is " + numDocs + " but tvx size is " + tvx.GetFilePointer() + " file=" + tvx.ToString() + "; now aborting this merge to prevent index corruption");
}
}
diff --git a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/TermInfosWriter.cs b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/TermInfosWriter.cs
index f5bbc1f9a9..d8457f853d 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Lucene3x/TermInfosWriter.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Lucene3x/TermInfosWriter.cs
@@ -1,4 +1,4 @@
-using J2N.Text;
+using J2N.Text;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Store;
@@ -107,9 +107,7 @@ internal TermInfosWriter(Directory directory, string segment, FieldInfos fis, in
{
directory.DeleteFile(IndexFileNames.SegmentFileName(segment, "", (isIndex ? Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION : Lucene3xPostingsFormat.TERMS_EXTENSION)));
}
-#pragma warning disable 168, IDE0059
- catch (IOException ignored)
-#pragma warning restore 168, IDE0059
+ catch (Exception ignored) when (ignored.IsIOException())
{
}
}
@@ -148,9 +146,7 @@ private void Initialize(Directory directory, string segment, FieldInfos fis, int
{
directory.DeleteFile(IndexFileNames.SegmentFileName(segment, "", (isIndex ? Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION : Lucene3xPostingsFormat.TERMS_EXTENSION)));
}
-#pragma warning disable 168, IDE0059
- catch (IOException ignored)
-#pragma warning restore 168, IDE0059
+ catch (Exception ignored) when (ignored.IsIOException())
{
}
}
diff --git a/src/Lucene.Net.TestFramework/Codecs/Lucene40/Lucene40DocValuesWriter.cs b/src/Lucene.Net.TestFramework/Codecs/Lucene40/Lucene40DocValuesWriter.cs
index 683c5cab86..a4deba480d 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Lucene40/Lucene40DocValuesWriter.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Lucene40/Lucene40DocValuesWriter.cs
@@ -606,7 +606,7 @@ private void AddVarSortedBytesField(FieldInfo field, IndexOutput data, IndexOutp
public override void AddSortedSetField(FieldInfo field, IEnumerable values, IEnumerable docToOrdCount, IEnumerable ords)
{
- throw new NotSupportedException("Lucene 4.0 does not support SortedSet docvalues");
+ throw UnsupportedOperationException.Create("Lucene 4.0 does not support SortedSet docvalues");
}
protected override void Dispose(bool disposing)
diff --git a/src/Lucene.Net.TestFramework/Codecs/Lucene42/Lucene42DocValuesConsumer.cs b/src/Lucene.Net.TestFramework/Codecs/Lucene42/Lucene42DocValuesConsumer.cs
index c0b3d9c961..e8564c25f0 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Lucene42/Lucene42DocValuesConsumer.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Lucene42/Lucene42DocValuesConsumer.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Diagnostics;
+using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
@@ -407,9 +407,9 @@ public bool MoveNext()
{
EncodeValues(count);
}
- catch (IOException bogus)
+ catch (Exception bogus) when (bogus.IsIOException())
{
- throw new Exception(bogus.ToString(), bogus);
+ throw RuntimeException.Create(bogus);
}
@ref.Bytes = buffer;
diff --git a/src/Lucene.Net.TestFramework/Codecs/Lucene42/Lucene42FieldInfosWriter.cs b/src/Lucene.Net.TestFramework/Codecs/Lucene42/Lucene42FieldInfosWriter.cs
index 439c184992..f08d05f658 100644
--- a/src/Lucene.Net.TestFramework/Codecs/Lucene42/Lucene42FieldInfosWriter.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/Lucene42/Lucene42FieldInfosWriter.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Diagnostics;
+using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
@@ -132,7 +132,7 @@ private static sbyte DocValuesByte(DocValuesType type)
}
else
{
- throw new InvalidOperationException();
+ throw AssertionError.Create();
}
}
}
diff --git a/src/Lucene.Net.TestFramework/Codecs/MissingOrdRemapper.cs b/src/Lucene.Net.TestFramework/Codecs/MissingOrdRemapper.cs
index cf0e6c30f6..541febf698 100644
--- a/src/Lucene.Net.TestFramework/Codecs/MissingOrdRemapper.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/MissingOrdRemapper.cs
@@ -89,7 +89,7 @@ public bool MoveNext()
object IEnumerator.Current => Current;
public void Reset()
- => throw new NotSupportedException();
+ => throw UnsupportedOperationException.Create();
public void Dispose()
=> @in.Dispose();
@@ -149,7 +149,7 @@ public bool MoveNext()
object IEnumerator.Current => Current;
public void Reset()
- => throw new NotSupportedException();
+ => throw UnsupportedOperationException.Create();
public void Dispose()
=> @in.Dispose();
@@ -208,7 +208,7 @@ public bool MoveNext()
object IEnumerator.Current => Current;
public void Reset()
- => throw new NotSupportedException();
+ => throw UnsupportedOperationException.Create();
public void Dispose()
=> @in.Dispose();
diff --git a/src/Lucene.Net.TestFramework/Codecs/MockRandom/MockRandomPostingsFormat.cs b/src/Lucene.Net.TestFramework/Codecs/MockRandom/MockRandomPostingsFormat.cs
index 6ca444563c..7c9628cdc0 100644
--- a/src/Lucene.Net.TestFramework/Codecs/MockRandom/MockRandomPostingsFormat.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/MockRandom/MockRandomPostingsFormat.cs
@@ -50,7 +50,7 @@ public RandomAnonymousClassHelper()
public override int Next(int maxValue)
{
- throw new InvalidOperationException("Please use MockRandomPostingsFormat(Random)");
+ throw IllegalStateException.Create("Please use MockRandomPostingsFormat(Random)");
}
}
diff --git a/src/Lucene.Net.TestFramework/Codecs/RAMOnly/RAMOnlyPostingsFormat.cs b/src/Lucene.Net.TestFramework/Codecs/RAMOnly/RAMOnlyPostingsFormat.cs
index bee1234c64..990f5667b5 100644
--- a/src/Lucene.Net.TestFramework/Codecs/RAMOnly/RAMOnlyPostingsFormat.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/RAMOnly/RAMOnlyPostingsFormat.cs
@@ -253,7 +253,7 @@ public override TermsConsumer AddField(FieldInfo field)
// LUCENENET specific - to avoid boxing, changed from CompareTo() to IndexOptionsComparer.Compare()
if (IndexOptionsComparer.Default.Compare(field.IndexOptions, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0)
{
- throw new NotSupportedException("this codec cannot index offsets");
+ throw UnsupportedOperationException.Create("this codec cannot index offsets");
}
RAMField ramField = new RAMField(field.Name, field);
postings.fieldToTerms[field.Name] = ramField;
@@ -420,10 +420,10 @@ public override SeekStatus SeekCeil(BytesRef term)
}
public override void SeekExact(long ord)
- => throw new NotSupportedException();
+ => throw UnsupportedOperationException.Create();
public override long Ord
- => throw new NotSupportedException();
+ => throw UnsupportedOperationException.Create();
// TODO: reuse BytesRef
public override BytesRef Term => new BytesRef(current);
diff --git a/src/Lucene.Net.TestFramework/Index/AssertingAtomicReader.cs b/src/Lucene.Net.TestFramework/Index/AssertingAtomicReader.cs
index cb3dba50fe..7ed3d5da23 100644
--- a/src/Lucene.Net.TestFramework/Index/AssertingAtomicReader.cs
+++ b/src/Lucene.Net.TestFramework/Index/AssertingAtomicReader.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Diagnostics;
+using Lucene.Net.Diagnostics;
using Lucene.Net.Search;
using Lucene.Net.Util;
using Lucene.Net.Util.Automaton;
@@ -111,7 +111,7 @@ public AssertingDocsEnum(DocsEnum @in, bool failOnUnsupportedDocID)
int docid = @in.DocID;
if (Debugging.AssertsEnabled) Debugging.Assert(docid == -1, "{0}: invalid initial doc id: {1}", @in.GetType(), docid);
}
- catch (NotSupportedException /*e*/)
+ catch (Exception e) when (e.IsUnsupportedOperationException())
{
if (failOnUnsupportedDocID)
{
diff --git a/src/Lucene.Net.TestFramework/Index/BaseDocValuesFormatTestCase.cs b/src/Lucene.Net.TestFramework/Index/BaseDocValuesFormatTestCase.cs
index 383edce745..a270fe8296 100644
--- a/src/Lucene.Net.TestFramework/Index/BaseDocValuesFormatTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Index/BaseDocValuesFormatTestCase.cs
@@ -3077,7 +3077,7 @@ public virtual void TestHugeBinaryValues()
{
w.AddDocument(doc);
}
- catch (ArgumentException iae)
+ catch (Exception iae) when (iae.IsIllegalArgumentException())
{
if (iae.Message.IndexOf("is too large", StringComparison.Ordinal) == -1)
{
@@ -3100,7 +3100,7 @@ public virtual void TestHugeBinaryValues()
{
r = w.GetReader();
}
- catch (ArgumentException iae)
+ catch (Exception iae) when (iae.IsIllegalArgumentException())
{
if (iae.Message.IndexOf("is too large", StringComparison.Ordinal) == -1)
{
@@ -3355,9 +3355,9 @@ public override void Run()
}
TestUtil.CheckReader(ir);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
}
@@ -3544,9 +3544,9 @@ public override void Run()
}
TestUtil.CheckReader(ir);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
}
diff --git a/src/Lucene.Net.TestFramework/Index/BaseMergePolicyTestCase.cs b/src/Lucene.Net.TestFramework/Index/BaseMergePolicyTestCase.cs
index 5ca34224d4..ed3663f69b 100644
--- a/src/Lucene.Net.TestFramework/Index/BaseMergePolicyTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Index/BaseMergePolicyTestCase.cs
@@ -1,5 +1,6 @@
using J2N.Threading.Atomic;
using Lucene.Net.Analysis;
+using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Store;
@@ -94,7 +95,7 @@ public override void Merge(IndexWriter writer, MergeTrigger trigger, bool newMer
{
if (!mayMerge.Value && writer.NextMerge() != null)
{
- throw new InvalidOperationException();
+ throw AssertionError.Create();
}
base.Merge(writer, trigger, newMergesFound);
}
diff --git a/src/Lucene.Net.TestFramework/Index/BasePostingsFormatTestCase.cs b/src/Lucene.Net.TestFramework/Index/BasePostingsFormatTestCase.cs
index 5626525d6a..7bb9aaa367 100644
--- a/src/Lucene.Net.TestFramework/Index/BasePostingsFormatTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Index/BasePostingsFormatTestCase.cs
@@ -1136,9 +1136,9 @@ public override void Run()
{
testCase.TestTermsOneThread(fieldsSource, options, maxTestOptions, maxIndexOptions, alwaysTestMax);
}
- catch (Exception t)
+ catch (Exception t) when (t.IsThrowable())
{
- throw new Exception(t.Message, t);
+ throw RuntimeException.Create(t);
}
}
finally
@@ -1285,11 +1285,11 @@ private static void TestFields(Fields fields) // LUCENENET: CA1822: Mark members
while (iterator.MoveNext())
{
var _ = iterator.Current;
- // .NET: Testing for iterator.Remove() isn't applicable
+ // LUCENENET: Testing for iterator.Remove() isn't applicable
}
Assert.IsFalse(iterator.MoveNext());
- // .NET: Testing for NoSuchElementException with .NET iterators isn't applicable
+ // LUCENENET: Testing for NoSuchElementException with .NET iterators isn't applicable
}
///
diff --git a/src/Lucene.Net.TestFramework/Index/BaseStoredFieldsFormatTestCase.cs b/src/Lucene.Net.TestFramework/Index/BaseStoredFieldsFormatTestCase.cs
index 1e5418cb5a..f827b4044c 100644
--- a/src/Lucene.Net.TestFramework/Index/BaseStoredFieldsFormatTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Index/BaseStoredFieldsFormatTestCase.cs
@@ -17,6 +17,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
+using System.Runtime.ExceptionServices;
using System.Text;
using JCG = J2N.Collections.Generic;
using Console = Lucene.Net.Util.SystemConsole;
@@ -515,7 +516,7 @@ public virtual void TestConcurrentReads()
} // rd.Dispose();
if (ex.Value != null)
{
- throw ex.Value;
+ ExceptionDispatchInfo.Capture(ex.Value).Throw(); // LUCENENET: Rethrow to preserve stack details from the other thread
}
}
@@ -554,21 +555,21 @@ public override void Run()
if (topDocs.TotalHits != 1)
{
Console.WriteLine(query);
- throw new InvalidOperationException("Expected 1 hit, got " + topDocs.TotalHits);
+ throw IllegalStateException.Create("Expected 1 hit, got " + topDocs.TotalHits);
}
Document sdoc = rd.Document(topDocs.ScoreDocs[0].Doc);
if (sdoc == null || sdoc.Get("fld") == null)
{
- throw new InvalidOperationException("Could not find document " + q);
+ throw IllegalStateException.Create("Could not find document " + q);
}
if (!Convert.ToString(q, CultureInfo.InvariantCulture).Equals(sdoc.Get("fld"), StringComparison.Ordinal))
{
- throw new InvalidOperationException("Expected " + q + ", but got " + sdoc.Get("fld"));
+ throw IllegalStateException.Create("Expected " + q + ", but got " + sdoc.Get("fld"));
}
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- ex.Value = e;
+ ex.CompareAndSet(null, e);
}
}
}
diff --git a/src/Lucene.Net.TestFramework/Index/BaseTermVectorsFormatTestCase.cs b/src/Lucene.Net.TestFramework/Index/BaseTermVectorsFormatTestCase.cs
index f6451e8fee..ca544a2af3 100644
--- a/src/Lucene.Net.TestFramework/Index/BaseTermVectorsFormatTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Index/BaseTermVectorsFormatTestCase.cs
@@ -15,7 +15,6 @@
using JCG = J2N.Collections.Generic;
using static Lucene.Net.Index.TermsEnum;
using Assert = Lucene.Net.TestFramework.Assert;
-using AssertionError = Lucene.Net.Diagnostics.AssertionException;
using Attribute = Lucene.Net.Util.Attribute;
using System.Diagnostics.CodeAnalysis;
using RandomizedTesting.Generators;
@@ -125,7 +124,7 @@ public OptionsWrapper(Options opt)
break;
default:
- throw new InvalidOperationException("Invalid Options enum type");
+ throw new ArgumentOutOfRangeException(nameof(opt), "Invalid Options enum type");
}
}
@@ -630,28 +629,19 @@ protected virtual void AssertEquals(RandomTokenStream tk, FieldType ft, Terms te
Assert.IsTrue(foundPayload);
}
}
-
- // LUCENENET specific - In Lucene, there were assertions set up inside TVReaders which throw AssertionError
- // (provided assertions are enabled), which in turn signaled this class to skip the check by catching AssertionError.
- // In .NET, assertions are not included in the release and cannot be enabled, so there is nothing to catch.
- // We have to explicitly exclude the types that rely on this behavior from the check. Otherwise, they would fall
- // through to Assert.Fail().
- //
- // We also have a fake AssertionException for testing mocks. We cannot throw InvalidOperationException in those
- // cases because that exception is expected in other contexts.
- Assert.ThrowsAnyOf(() => docsAndPositionsEnum.NextPosition());
-
-// try
-// {
-// docsAndPositionsEnum.NextPosition();
-// Assert.Fail();
-// }
-//#pragma warning disable 168
-// catch (Exception e)
-//#pragma warning restore 168
-// {
-// // ok
-// }
+ try
+ {
+ docsAndPositionsEnum.NextPosition();
+ Assert.Fail();
+ }
+ catch (Exception e) when (e.IsException())
+ {
+ // ok
+ }
+ catch (Exception e) when (e.IsAssertionError())
+ {
+ // ok
+ }
}
Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsAndPositionsEnum.NextDoc());
}
@@ -964,7 +954,7 @@ public override void Run()
outerInstance.AssertEquals(docs[idx], reader.GetTermVectors(docID));
}
}
- catch (Exception t)
+ catch (Exception t) when (t.IsThrowable())
{
this.exception.Value = t;
}
diff --git a/src/Lucene.Net.TestFramework/Index/ThreadedIndexingAndSearchingTestCase.cs b/src/Lucene.Net.TestFramework/Index/ThreadedIndexingAndSearchingTestCase.cs
index 193c1298d5..cbe7e44929 100644
--- a/src/Lucene.Net.TestFramework/Index/ThreadedIndexingAndSearchingTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Index/ThreadedIndexingAndSearchingTestCase.cs
@@ -386,13 +386,13 @@ public override void Run()
doc.RemoveField(addedField);
}
}
- catch (Exception t)
+ catch (Exception t) when (t.IsThrowable())
{
Console.WriteLine(Thread.CurrentThread.Name + ": hit exc");
Console.WriteLine(t.ToString());
Console.Write(t.StackTrace);
outerInstance.m_failed.Value = (true);
- throw new Exception(t.ToString(), t);
+ throw RuntimeException.Create(t);
}
}
if (Verbose)
@@ -532,12 +532,12 @@ public override void Run()
outerInstance.ReleaseSearcher(s);
}
}
- catch (Exception t)
+ catch (Exception t) when (t.IsThrowable())
{
Console.WriteLine(Thread.CurrentThread.Name + ": hit exc");
outerInstance.m_failed.Value = (true);
Console.WriteLine(t.ToString());
- throw new Exception(t.ToString(), t);
+ throw RuntimeException.Create(t);
}
}
}
diff --git a/src/Lucene.Net.TestFramework/Lucene.Net.TestFramework.csproj b/src/Lucene.Net.TestFramework/Lucene.Net.TestFramework.csproj
index e18189aac2..372aa91e9a 100644
--- a/src/Lucene.Net.TestFramework/Lucene.Net.TestFramework.csproj
+++ b/src/Lucene.Net.TestFramework/Lucene.Net.TestFramework.csproj
@@ -103,6 +103,8 @@
+
+
diff --git a/src/Lucene.Net.TestFramework/Search/AssertingBulkScorer.cs b/src/Lucene.Net.TestFramework/Search/AssertingBulkScorer.cs
index 8f8b8388bf..9db42c50f0 100644
--- a/src/Lucene.Net.TestFramework/Search/AssertingBulkScorer.cs
+++ b/src/Lucene.Net.TestFramework/Search/AssertingBulkScorer.cs
@@ -64,9 +64,7 @@ public override void Score(ICollector collector)
bool remaining = @in.Score(collector, DocsEnum.NO_MORE_DOCS);
if (Debugging.AssertsEnabled) Debugging.Assert(!remaining);
}
-#pragma warning disable 168, IDE0059
- catch (NotSupportedException e)
-#pragma warning restore 168, IDE0059
+ catch (Exception e) when (e.IsUnsupportedOperationException())
{
@in.Score(collector);
}
diff --git a/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs b/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs
index 00d2a7bf86..907a59b3a6 100644
--- a/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs
+++ b/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs
@@ -73,12 +73,12 @@ public AssertingWeightAnonymousClass(Random random, Weight w)
public override void Normalize(float norm, float topLevelBoost)
{
- throw new InvalidOperationException("Weight already normalized.");
+ throw IllegalStateException.Create("Weight already normalized.");
}
public override float GetValueForNormalization()
{
- throw new InvalidOperationException("Weight already normalized.");
+ throw IllegalStateException.Create("Weight already normalized.");
}
}
diff --git a/src/Lucene.Net.TestFramework/Search/CheckHits.cs b/src/Lucene.Net.TestFramework/Search/CheckHits.cs
index 939479bcd5..5ccfbc712c 100644
--- a/src/Lucene.Net.TestFramework/Search/CheckHits.cs
+++ b/src/Lucene.Net.TestFramework/Search/CheckHits.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Index;
+using Lucene.Net.Index;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
@@ -400,25 +400,21 @@ public static void VerifyExplanation(string q, int doc, float score, bool deep,
{
k1 += "max plus ".Length;
int k2 = descr.IndexOf(" ", k1, StringComparison.Ordinal);
- try
- {
- // LUCENENET NOTE: Using current culture here is intentional because
- // we are parsing from text that was made using the current culture.
- x = Convert.ToSingle(descr.Substring(k1, k2 - k1).Trim());
- if (descr.Substring(k2).Trim().Equals("times others of:", StringComparison.Ordinal))
- {
- maxTimesOthers = true;
- }
- }
-#pragma warning disable 168, IDE0059
- catch (FormatException e)
-#pragma warning restore 168, IDE0059
+
+ // LUCENENET NOTE: Using current culture here is intentional because
+ // we are parsing from text that was made using the current culture.
+ if (float.TryParse(descr.Substring(k1, k2 - k1).Trim(), out x) &&
+ descr.Substring(k2).Trim().Equals("times others of:", StringComparison.Ordinal))
{
+ maxTimesOthers = true;
}
}
}
// TODO: this is a TERRIBLE assertion!!!!
- Assert.IsTrue(productOf || sumOf || maxOf || maxTimesOthers, q + ": multi valued explanation description=\"" + descr + "\" must be 'max of plus x times others' or end with 'product of'" + " or 'sum of:' or 'max of:' - " + expl);
+ Assert.IsTrue(productOf || sumOf || maxOf || maxTimesOthers,
+ q + ": multi valued explanation description=\"" + descr
+ + "\" must be 'max of plus x times others' or end with 'product of'"
+ + " or 'sum of:' or 'max of:' - " + expl);
float sum = 0;
float product = 1;
float max = 0;
@@ -451,7 +447,8 @@ public static void VerifyExplanation(string q, int doc, float score, bool deep,
{
Assert.IsTrue(false, "should never get here!");
}
- Assert.AreEqual(combined, value, ExplainToleranceDelta(combined, value), q + ": actual subDetails combined==" + combined + " != value=" + value + " Explanation: " + expl);
+ Assert.AreEqual(combined, value, ExplainToleranceDelta(combined, value),
+ q + ": actual subDetails combined==" + combined + " != value=" + value + " Explanation: " + expl);
}
}
}
@@ -580,9 +577,9 @@ public virtual void Collect(int doc)
{
exp = s.Explain(q, doc);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception("exception in hitcollector of [[" + d + "]] for #" + doc, e);
+ throw RuntimeException.Create("exception in hitcollector of [[" + d + "]] for #" + doc, e);
}
Assert.IsNotNull(exp, "Explanation of [[" + d + "]] for #" + doc + " is null");
diff --git a/src/Lucene.Net.TestFramework/Search/QueryUtils.cs b/src/Lucene.Net.TestFramework/Search/QueryUtils.cs
index 083db1c894..5daf33f51d 100644
--- a/src/Lucene.Net.TestFramework/Search/QueryUtils.cs
+++ b/src/Lucene.Net.TestFramework/Search/QueryUtils.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Analysis;
+using Lucene.Net.Analysis;
using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index;
@@ -157,9 +157,9 @@ public static void Check(Random random, Query q1, IndexSearcher s, bool wrap)
CheckEqual(s.Rewrite(q1), s.Rewrite(q2));
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
#else
@@ -207,9 +207,9 @@ public static void Check(LuceneTestCase luceneTestCase, Random random, Query q1,
CheckEqual(s.Rewrite(q1), s.Rewrite(q2));
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
#endif
@@ -285,9 +285,9 @@ private static IndexReader[] LoadEmptyReaders() // LUCENENET: Avoid static const
emptyReaders[5] = MakeEmptyIndex(new Random(0), 5);
emptyReaders[7] = MakeEmptyIndex(new Random(0), 7);
}
- catch (IOException ex)
+ catch (Exception ex) when (ex.IsIOException())
{
- throw new Exception(ex.ToString(), ex);
+ throw RuntimeException.Create(ex);
}
return emptyReaders;
}
@@ -454,12 +454,12 @@ public virtual void Collect(int doc)
{
sbord.Append(order[i] == skip_op ? " skip()" : " next()");
}
- throw new Exception("ERROR matching docs:" + "\n\t" + (doc != scorerDoc ? "--> " : "") + "doc=" + doc + ", scorerDoc=" + scorerDoc + "\n\t" + (!more ? "--> " : "") + "tscorer.more=" + more + "\n\t" + (scoreDiff > maxDiff ? "--> " : "") + "scorerScore=" + scorerScore + " scoreDiff=" + scoreDiff + " maxDiff=" + maxDiff + "\n\t" + (scorerDiff > maxDiff ? "--> " : "") + "scorerScore2=" + scorerScore2 + " scorerDiff=" + scorerDiff + "\n\thitCollector.Doc=" + doc + " score=" + score + "\n\t Scorer=" + scorer + "\n\t Query=" + q + " " + q.GetType().Name + "\n\t Searcher=" + s + "\n\t Order=" + sbord + "\n\t Op=" + (op == skip_op ? " skip()" : " next()"));
+ throw RuntimeException.Create("ERROR matching docs:" + "\n\t" + (doc != scorerDoc ? "--> " : "") + "doc=" + doc + ", scorerDoc=" + scorerDoc + "\n\t" + (!more ? "--> " : "") + "tscorer.more=" + more + "\n\t" + (scoreDiff > maxDiff ? "--> " : "") + "scorerScore=" + scorerScore + " scoreDiff=" + scoreDiff + " maxDiff=" + maxDiff + "\n\t" + (scorerDiff > maxDiff ? "--> " : "") + "scorerScore2=" + scorerScore2 + " scorerDiff=" + scorerDiff + "\n\thitCollector.Doc=" + doc + " score=" + score + "\n\t Scorer=" + scorer + "\n\t Query=" + q + " " + q.GetType().Name + "\n\t Searcher=" + s + "\n\t Order=" + sbord + "\n\t Op=" + (op == skip_op ? " skip()" : " next()"));
}
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
@@ -605,9 +605,9 @@ public virtual void Collect(int doc)
}
lastDoc[0] = doc;
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
diff --git a/src/Lucene.Net.TestFramework/Search/RandomOrderCollector.cs b/src/Lucene.Net.TestFramework/Search/RandomOrderCollector.cs
index 4db7adccbc..f59bb4993d 100644
--- a/src/Lucene.Net.TestFramework/Search/RandomOrderCollector.cs
+++ b/src/Lucene.Net.TestFramework/Search/RandomOrderCollector.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Index;
+using Lucene.Net.Index;
using System;
namespace Lucene.Net.Search
@@ -100,7 +100,7 @@ public void Collect(int doc)
{
freqs[buffered] = scorer.Freq;
}
- catch (NotSupportedException)
+ catch (Exception e) when (e.IsUnsupportedOperationException())
{
freqs[buffered] = -1;
}
@@ -114,6 +114,6 @@ public bool AcceptsDocsOutOfOrder
=> @in.AcceptsDocsOutOfOrder;
public void SetNextReader(AtomicReaderContext context)
- => throw new NotSupportedException();
+ => throw UnsupportedOperationException.Create();
}
}
\ No newline at end of file
diff --git a/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs b/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs
index 012281b513..6f1651e025 100644
--- a/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs
+++ b/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs
@@ -45,7 +45,7 @@ namespace Lucene.Net.Search
#if FEATURE_SERIALIZABLE_EXCEPTIONS
[Serializable]
#endif
- public class SearcherExpiredException : Exception
+ public class SearcherExpiredException : Exception, IRuntimeException // LUCENENET specific: Added IRuntimeException for identification of the Java superclass in .NET
{
public SearcherExpiredException(string message)
: base(message)
@@ -743,11 +743,11 @@ public override void Run()
}
}
}
- catch (Exception t)
+ catch (Exception t) when (t.IsThrowable())
{
Console.WriteLine("FAILED:");
Console.Out.WriteLine(t.StackTrace);
- throw new Exception(t.Message, t);
+ throw RuntimeException.Create(t);
}
}
}
diff --git a/src/Lucene.Net.TestFramework/Store/BaseDirectoryTestCase.cs b/src/Lucene.Net.TestFramework/Store/BaseDirectoryTestCase.cs
index d9475637c5..febe528af5 100644
--- a/src/Lucene.Net.TestFramework/Store/BaseDirectoryTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Store/BaseDirectoryTestCase.cs
@@ -153,10 +153,15 @@ public virtual void TestDeleteFile()
dir.DeleteFile("foo.txt");
Assert.IsFalse(ContainsFile(dir, file));
- Assert.ThrowsAnyOf(() =>
+ try
{
dir.DeleteFile("foo.txt");
- });
+ fail();
+ }
+ catch (Exception e) when (e.IsNoSuchFileExceptionOrFileNotFoundException())
+ {
+ // expected
+ }
}
[Test]
@@ -276,7 +281,7 @@ public virtual void TestVInt64() // LUCENENET: Renamed from TestVLong
// ints[i] = (Random.nextBoolean() ? -1 : 1) * Random.nextInt(1024);
// break;
// default:
- // throw new AssertionError();
+ // throw AssertionError.Create();
// }
// }
@@ -321,7 +326,7 @@ public virtual void TestVInt64() // LUCENENET: Renamed from TestVLong
// longs[i] = (Random.nextBoolean() ? -1 : 1) * Random.nextInt(1024);
// break;
// default:
- // throw new AssertionError();
+ // throw AssertionError.Create();
// }
// }
@@ -505,7 +510,7 @@ public virtual void TestDetectClose()
// assertTrue(SlowFileExists(this.dir, fileName));
// }
// }
- // //catch (IOException e)
+ // //catch (Exception e) when (e.IsIOException())
// //{
// // throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
// //}
@@ -551,12 +556,12 @@ public virtual void TestDetectClose()
// // Just open, nothing else.
// }
- // catch (UnauthorizedAccessException e)
+ // catch (Exception e) when (e.IsAccessDeniedException())
// {
// // Access denied is allowed for files for which the output is still open (MockDirectoryWriter enforces
// // this, for example). Since we don't synchronize with the writer thread, just ignore it.
// }
- // catch (IOException e)
+ // catch (Exception e) when (e.IsIOException())
// {
// throw new IOException("Something went wrong when opening: " + file, e);
// }
@@ -564,7 +569,7 @@ public virtual void TestDetectClose()
// }
// }
// }
- // catch (IOException e)
+ // catch (Exception e) when (e.IsIOException())
// {
// //throw new UncheckedIOException(e);
// throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
@@ -718,10 +723,15 @@ public virtual void TestNoDir()
tempDir.Delete();
//IOUtils.rm(tempDir);
using Directory dir = GetDirectory(tempDir);
- Assert.ThrowsAnyOf(() =>
+ try
{
DirectoryReader.Open(dir);
- });
+ fail();
+ }
+ catch (Exception e) when (e.IsNoSuchFileExceptionOrFileNotFoundException())
+ {
+ // expected
+ }
}
[Test]
@@ -818,9 +828,9 @@ private class CopyBytesThread : ThreadJob
public CopyBytesThread(Barrier start, IndexInput input, Directory d, int i)
{
- this.start = start ?? throw new ArgumentNullException(nameof(start));
+ this.start = start ?? throw new ArgumentNullException(nameof(start)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
this.src = (IndexInput)input.Clone();
- this.d = d ?? throw new ArgumentNullException(nameof(d));
+ this.d = d ?? throw new ArgumentNullException(nameof(d)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention)
this.i = i;
}
@@ -832,9 +842,9 @@ public override void Run()
using IndexOutput dst = d.CreateOutput("copy" + i, IOContext.DEFAULT);
dst.CopyBytes(src, src.Length - 100);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception(e.ToString(), e);
+ throw RuntimeException.Create(e);
}
}
}
@@ -912,10 +922,15 @@ public virtual void TestFsyncDoesntCreateNewFiles()
int fileCount = fsdir.ListAll().Length;
// fsync it
- Assert.ThrowsAnyOf(() =>
+ try
{
fsdir.Sync(new string[] { "afile" });
- });
+ fail();
+ }
+ catch (Exception e) when (e.IsNoSuchFileExceptionOrFileNotFoundException())
+ {
+ // expected
+ }
// no new files created
assertEquals(fileCount, fsdir.ListAll().Length);
@@ -1436,22 +1451,22 @@ public virtual void TestSeekToEndOfFile()
// Assert.IsFalse(ContainsFile(fsDir, fileName));
// // Make sure fileLength claims it's deleted:
- // Assert.Throws(() => {
+ // Assert.Throws(() => { // LUCENENET: If this is ever uncommented, we need to use e.IsNoSuchFileExceptionOrFileNotFoundException()
// fsDir.FileLength(fileName);
// });
// // Make sure rename fails:
- // Assert.Throws(() => {
+ // Assert.Throws(() => { // LUCENENET: If this is ever uncommented, we need to use e.IsNoSuchFileExceptionOrFileNotFoundException()
// fsDir.Rename(fileName, "file2");
// });
// // Make sure delete fails:
- // Assert.Throws(() => {
+ // Assert.Throws(() => { // LUCENENET: If this is ever uncommented, we need to use e.IsNoSuchFileExceptionOrFileNotFoundException()
// fsDir.DeleteFile(fileName);
// });
// // Make sure we cannot open it for reading:
- // Assert.Throws(() => {
+ // Assert.Throws(() => { // LUCENENET: If this is ever uncommented, we need to use e.IsNoSuchFileExceptionOrFileNotFoundException()
// fsDir.OpenInput(fileName, IOContext.DEFAULT);
// });
// }
diff --git a/src/Lucene.Net.TestFramework/Store/MockDirectoryWrapper.cs b/src/Lucene.Net.TestFramework/Store/MockDirectoryWrapper.cs
index 98c96bcdc9..51319e79ee 100644
--- a/src/Lucene.Net.TestFramework/Store/MockDirectoryWrapper.cs
+++ b/src/Lucene.Net.TestFramework/Store/MockDirectoryWrapper.cs
@@ -13,7 +13,6 @@
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
-using AssertionError = Lucene.Net.Diagnostics.AssertionException;
using Console = Lucene.Net.Util.SystemConsole;
using JCG = J2N.Collections.Generic;
#if FEATURE_SERIALIZABLE_EXCEPTIONS
@@ -305,9 +304,7 @@ public virtual void Crash()
{
f.Dispose();
}
-#pragma warning disable 168
- catch (Exception ignored)
-#pragma warning restore 168
+ catch (Exception ignored) when (ignored.IsException())
{
//Debug.WriteLine("Crash(): f.Dispose() FAILED for {0}:\n{1}", f.ToString(), ignored.ToString());
}
@@ -575,7 +572,7 @@ private void DeleteFile(string name, bool forced)
}
else
{
- throw WithAdditionalErrorInformation(new AssertionError("MockDirectoryWrapper: file \"" + name + "\" is still open: cannot delete"), name, true);
+ throw WithAdditionalErrorInformation(AssertionError.Create("MockDirectoryWrapper: file \"" + name + "\" is still open: cannot delete"), name, true);
}
}
else
@@ -634,7 +631,7 @@ public override IndexOutput CreateOutput(string name, IOContext context)
}
else
{
- throw new AssertionError("MockDirectoryWrapper: file \"" + name + "\" is still open: cannot overwrite");
+ throw AssertionError.Create("MockDirectoryWrapper: file \"" + name + "\" is still open: cannot overwrite");
}
}
@@ -717,7 +714,7 @@ internal void AddFileHandle(IDisposable c, string name, Handle handle)
openFiles[name] = 1;
}
- openFileHandles[c] = new Exception("unclosed Index" + handle.ToString() + ": " + name);
+ openFileHandles[c] = RuntimeException.Create("unclosed Index" + handle.ToString() + ": " + name);
}
}
@@ -870,12 +867,12 @@ protected override void Dispose(bool disposing)
// RuntimeException instead ofIOException because
// super() does not throw IOException currently:
- throw new Exception("MockDirectoryWrapper: cannot close: there are still open files: "
+ throw RuntimeException.Create("MockDirectoryWrapper: cannot close: there are still open files: "
+ Collections.ToString(openFiles), cause);
}
if (openLocks.Count > 0)
{
- throw new Exception("MockDirectoryWrapper: cannot close: there are still open locks: "
+ throw RuntimeException.Create("MockDirectoryWrapper: cannot close: there are still open locks: "
+ Collections.ToString(openLocks));
}
@@ -940,9 +937,7 @@ protected override void Dispose(bool disposing)
{
sis.Read(m_input, file);
}
-#pragma warning disable 168
- catch (IOException ioe)
-#pragma warning restore 168
+ catch (Exception ioe) when (ioe.IsIOException())
{
// OK: likely some of the .si files were deleted
}
@@ -964,7 +959,7 @@ protected override void Dispose(bool disposing)
}
}
}
- catch (Exception t)
+ catch (Exception t) when (t.IsThrowable())
{
Console.Error.WriteLine("ERROR processing leftover segments file " + file + ":");
Console.WriteLine(t.ToString());
diff --git a/src/Lucene.Net.TestFramework/Store/MockIndexInputWrapper.cs b/src/Lucene.Net.TestFramework/Store/MockIndexInputWrapper.cs
index 5f69f089a3..d453bf0240 100644
--- a/src/Lucene.Net.TestFramework/Store/MockIndexInputWrapper.cs
+++ b/src/Lucene.Net.TestFramework/Store/MockIndexInputWrapper.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
namespace Lucene.Net.Store
@@ -71,7 +71,7 @@ private void EnsureOpen()
{
if (closed)
{
- throw new Exception("Abusing closed IndexInput!");
+ throw RuntimeException.Create("Abusing closed IndexInput!");
}
}
@@ -92,7 +92,7 @@ public override object Clone()
v = Integer.valueOf(v.intValue()+1);
dir.openFiles.put(name, v);
} else {
- throw new RuntimeException("BUG: cloned file was not open?");
+ throw RuntimeException.Create("BUG: cloned file was not open?");
}
}
*/
diff --git a/src/Lucene.Net.TestFramework/Store/SlowOpeningMockIndexInputWrapper.cs b/src/Lucene.Net.TestFramework/Store/SlowOpeningMockIndexInputWrapper.cs
index eed0a9ff4b..d6f7ef5288 100644
--- a/src/Lucene.Net.TestFramework/Store/SlowOpeningMockIndexInputWrapper.cs
+++ b/src/Lucene.Net.TestFramework/Store/SlowOpeningMockIndexInputWrapper.cs
@@ -33,16 +33,15 @@ public SlowOpeningMockIndexInputWrapper(MockDirectoryWrapper dir, string name, I
{
Thread.Sleep(50);
}
- catch (ThreadInterruptedException /*ie*/)
+ catch (Exception ie) when (ie.IsInterruptedException())
{
try
{
base.Dispose();
} // we didnt open successfully
- catch (Exception)
+ catch (Exception ignore) when (ignore.IsThrowable())
{
}
- //throw new ThreadInterruptedException(ie.ToString(), ie);
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
}
diff --git a/src/Lucene.Net.TestFramework/Support/ExceptionHandling/ExceptionExtensions.cs b/src/Lucene.Net.TestFramework/Support/ExceptionHandling/ExceptionExtensions.cs
new file mode 100644
index 0000000000..f4fdd2c4ad
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/ExceptionHandling/ExceptionExtensions.cs
@@ -0,0 +1,63 @@
+using System;
+using System.Runtime.CompilerServices;
+
+namespace Lucene.Net
+{
+ /*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+ ///
+ /// Extension methods to close gaps when catching exceptions in .NET.
+ ///
+ /// These methods make it possible to catch only the types for a general exception
+ /// type in Java even though the exception inheritance structure is different in .NET
+ /// and does not map 1-to-1 with Java exceptions.
+ ///
+ /// This class contains "overrides" for the logic in production when we want different
+ /// behavior in tests. The syntax of the extension method in the test is exactly the same,
+ /// but the method may behave more accurately so we can make the tests more explicit.
+ ///
+ internal static class ExceptionExtensions
+ {
+ ///
+ /// Used to check whether corresponds to an IllegalArgumentException
+ /// in Java.
+ ///
+ /// NOTE: This method differs from but
+ /// since they use the same name, this is the default in the tests. This tests specifically for the
+ /// and will return false for or .
+ ///
+ /// In a nutshell, it is better in production code to catch and all subclasses
+ /// because that guarantees it will "just work" when we upgrade from using the Java-like
+ /// to the more specific or . But tests generally
+ /// are checking to make sure the guard clauses are implemented properly, so it is better to fail in cases where we are not precisely
+ /// catching . This way, the test can be updated and commented to indicate that we changed the behavior in .NET.
+ ///
+ /// This exception.
+ /// true if corresponds to an IllegalArgumentException type
+ /// in Java; otherwise false.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static bool IsIllegalArgumentException(this Exception e)
+ {
+ if (e is null || e.IsAlwaysIgnored()) return false;
+
+ return e is ArgumentException &&
+ !(e is ArgumentNullException) && // Corresponds to NullPointerException, so we don't catch it here.
+ !(e is ArgumentOutOfRangeException); // Corresponds to IndexOutOfBoundsException (and subclasses), so we don't catch it here.
+ }
+ }
+}
diff --git a/src/Lucene.Net.TestFramework/Support/JavaCompatibility/LuceneTestCase.cs b/src/Lucene.Net.TestFramework/Support/JavaCompatibility/LuceneTestCase.cs
index a83f718e6c..7b0da1a532 100644
--- a/src/Lucene.Net.TestFramework/Support/JavaCompatibility/LuceneTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Support/JavaCompatibility/LuceneTestCase.cs
@@ -1,6 +1,7 @@
-using Lucene.Net.Support;
+using Lucene.Net.Support;
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Runtime.CompilerServices;
using Assert = Lucene.Net.TestFramework.Assert;
using JCG = J2N.Collections.Generic;
@@ -40,246 +41,287 @@ public abstract partial class LuceneTestCase
// return Random;
//}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertTrue(bool condition)
{
Assert.IsTrue(condition);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertTrue(string message, bool condition)
{
Assert.IsTrue(condition, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertFalse(bool condition)
{
Assert.IsFalse(condition);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertFalse(string message, bool condition)
{
Assert.IsFalse(condition, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(T expected, T actual)
{
Assert.AreEqual(expected, actual);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, T expected, T actual)
{
Assert.AreEqual(expected, actual, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string expected, string actual)
{
Assert.AreEqual(expected, actual);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, string expected, string actual)
{
Assert.AreEqual(expected, actual, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(bool expected, bool actual)
{
Assert.AreEqual(expected, actual);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, bool expected, bool actual)
{
Assert.AreEqual(expected, actual, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(long expected, long actual)
{
Assert.AreEqual(expected, actual);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, long expected, long actual)
{
Assert.AreEqual(expected, actual, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(int expected, int actual)
{
Assert.AreEqual(expected, actual);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, int expected, int actual)
{
Assert.AreEqual(expected, actual, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(byte expected, byte actual)
{
Assert.AreEqual(expected, actual);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, byte expected, byte actual)
{
Assert.AreEqual(expected, actual, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(double d1, double d2, double delta)
{
Assert.AreEqual(d1, d2, delta);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string msg, float d1, float d2, float delta)
{
Assert.AreEqual(d1, d2, delta, msg);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(float d1, float d2, float delta)
{
Assert.AreEqual(d1, d2, delta);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string msg, double d1, double d2, double delta)
{
Assert.AreEqual(d1, d2, delta, msg);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(ISet expected, ISet actual, bool aggressive = true)
{
Assert.AreEqual(expected, actual, aggressive);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, ISet expected, ISet actual, bool aggressive = true)
{
Assert.AreEqual(expected, actual, aggressive, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(IList expected, IList actual, bool aggressive = true)
{
Assert.AreEqual(expected, actual, aggressive);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, IList expected, IList actual, bool aggressive = true)
{
Assert.AreEqual(expected, actual, aggressive, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(T[] expected, T[] actual)
{
Assert.AreEqual(expected, actual);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, T[] expected, T[] actual)
{
Assert.AreEqual(expected, actual, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(IDictionary expected, IDictionary actual, bool aggressive = true)
{
Assert.AreEqual(expected, actual, aggressive);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertEquals(string message, IDictionary expected, IDictionary actual, bool aggressive = true)
{
Assert.AreEqual(expected, actual, aggressive, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertNotSame(object unexpected, object actual)
{
Assert.AreNotSame(unexpected, actual);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertNotSame(string message, object unexpected, object actual)
{
Assert.AreNotSame(unexpected, actual, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertNotNull(object o)
{
Assert.NotNull(o);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertNotNull(string msg, object o)
{
Assert.NotNull(o, msg);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertNull(object o)
{
Assert.Null(o);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertNull(string msg, object o)
{
Assert.Null(o, msg);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertArrayEquals(T[] a1, T[] a2)
{
Assert.AreEqual(a1, a2);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertArrayEquals(string message, T[] a1, T[] a2)
{
Assert.AreEqual(a1, a2, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertArrayEquals(Func getMessage, T[] a1, T[] a2)
{
Assert.AreEqual(a1, a2, getMessage());
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertSame(object expected, object actual)
{
Assert.AreSame(expected, actual);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void assertSame(string message, object expected, object actual)
{
Assert.AreSame(expected, actual, message);
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void fail()
{
Assert.Fail();
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void fail(string message)
{
@@ -287,6 +329,7 @@ internal static void fail(string message)
}
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static ISet AsSet(params T[] args)
{
@@ -294,6 +337,7 @@ internal static ISet AsSet(params T[] args)
}
[ExceptionToNetNumericConvention] // LUCENENET: This is for making test porting easier, keeping as-is
+ [DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int randomInt(int max)
{
@@ -301,6 +345,7 @@ internal static int randomInt(int max)
}
[ExceptionToNetNumericConvention] // LUCENENET: This is for making test porting easier, keeping as-is
+ [DebuggerStepThrough]
internal static int randomIntBetween(int min, int max)
{
// LUCENENET specific - added guard clause instead of assert
@@ -318,6 +363,7 @@ internal static int randomIntBetween(int min, int max)
}
[ExceptionToNetNumericConvention] // LUCENENET: This is for making test porting easier, keeping as-is
+ [DebuggerStepThrough]
private static int toIntExact(long value)
{
if (value > int.MaxValue)
@@ -331,6 +377,7 @@ private static int toIntExact(long value)
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [DebuggerStepThrough]
internal double randomGaussian()
{
return RandomGaussian();
diff --git a/src/Lucene.Net.TestFramework/Support/JavaCompatibility/SystemTypesHelpers.cs b/src/Lucene.Net.TestFramework/Support/JavaCompatibility/SystemTypesHelpers.cs
index 4e8776ad15..599913d5e5 100644
--- a/src/Lucene.Net.TestFramework/Support/JavaCompatibility/SystemTypesHelpers.cs
+++ b/src/Lucene.Net.TestFramework/Support/JavaCompatibility/SystemTypesHelpers.cs
@@ -1,4 +1,4 @@
-using J2N;
+using J2N;
using System;
using System.Collections;
using System.Collections.Generic;
@@ -292,7 +292,12 @@ public static void retainAll(this ISet s, ISet other)
public static void printStackTrace(this Exception e)
{
- Console.WriteLine(e.StackTrace);
+ Console.Error.WriteLine(e.StackTrace);
+ }
+
+ public static void printStackTrace(this Exception e, TextWriter destination)
+ {
+ destination.WriteLine(e.StackTrace);
}
///
diff --git a/src/Lucene.Net.TestFramework/Support/Util/LuceneTestFrameworkInitializer.cs b/src/Lucene.Net.TestFramework/Support/Util/LuceneTestFrameworkInitializer.cs
index b0f23a79f2..2ad8ccd1c6 100644
--- a/src/Lucene.Net.TestFramework/Support/Util/LuceneTestFrameworkInitializer.cs
+++ b/src/Lucene.Net.TestFramework/Support/Util/LuceneTestFrameworkInitializer.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Codecs;
+using Lucene.Net.Codecs;
using Lucene.Net.Configuration;
using NUnit.Framework;
using System;
@@ -160,7 +160,7 @@ protected void OneTimeSetUpBeforeTests()
catch (Exception ex)
{
// Write the stack trace so we have something to go on if an error occurs here.
- throw new Exception($"An exception occurred during OneTimeSetUpBeforeTests:\n{ex}", ex);
+ throw RuntimeException.Create($"An exception occurred during OneTimeSetUpBeforeTests:\n{ex}", ex);
}
}
@@ -178,7 +178,7 @@ protected void OneTimeTearDownAfterTests()
catch (Exception ex)
{
// Write the stack trace so we have something to go on if an error occurs here.
- throw new Exception($"An exception occurred during OneTimeTearDownAfterTests:\n{ex}", ex);
+ throw RuntimeException.Create($"An exception occurred during OneTimeTearDownAfterTests:\n{ex}", ex);
}
// Cleanup our LineDocsFile and reset LuceneTestCase back to its original state.
@@ -227,6 +227,24 @@ private void Initialize()
// the ConfigurationFactory is set.
Lucene.Net.Diagnostics.Debugging.AssertsEnabled = SystemProperties.GetPropertyAsBoolean("assert", true);
+ // Identify NUnit exceptions down in Lucene.Net so they can be ignored in catch blocks that
+ // catch Java "Exception" types that do subclass Error (for the ExceptionExtensions.IsException() method).
+ Lucene.ExceptionExtensions.NUnitResultStateExceptionType = typeof(NUnit.Framework.ResultStateException);
+ Lucene.ExceptionExtensions.NUnitAssertionExceptionType = typeof(NUnit.Framework.AssertionException);
+ Lucene.ExceptionExtensions.NUnitMultipleAssertExceptionType = typeof(NUnit.Framework.MultipleAssertException);
+ Lucene.ExceptionExtensions.NUnitInconclusiveExceptionType = typeof(NUnit.Framework.InconclusiveException);
+ Lucene.ExceptionExtensions.NUnitSuccessExceptionType = typeof(NUnit.Framework.SuccessException);
+ Lucene.ExceptionExtensions.NUnitInvalidPlatformException = Type.GetType("NUnit.Framework.Internal.InvalidPlatformException, NUnit.Framework");
+
+ // Identify the Debug.Assert() exception so it can be excluded from being swallowed by catch blocks.
+ // These types are internal, so we can identify them using Reflection.
+ Lucene.ExceptionExtensions.DebugAssertExceptionType =
+ // .NET 5/.NET Core 3.x
+ Type.GetType("System.Diagnostics.DebugProvider+DebugAssertException, System.Private.CoreLib")
+ // .NET Core 2.x
+ ?? Type.GetType("System.Diagnostics.Debug+DebugAssertException, System.Private.CoreLib");
+ // .NET Framework doesn't throw in this case
+
AfterInitialization();
return new object(); // Placeholder to indicate our initializer has been run already
diff --git a/src/Lucene.Net.TestFramework/Util/Automaton/AutomatonTestUtil.cs b/src/Lucene.Net.TestFramework/Util/Automaton/AutomatonTestUtil.cs
index 7b9c6fe94b..812f984f4d 100644
--- a/src/Lucene.Net.TestFramework/Util/Automaton/AutomatonTestUtil.cs
+++ b/src/Lucene.Net.TestFramework/Util/Automaton/AutomatonTestUtil.cs
@@ -51,9 +51,7 @@ public static string RandomRegexp(Random r)
new RegExp(regexp, RegExpSyntax.NONE);
return regexp;
}
-#pragma warning disable 168, IDE0059
- catch (Exception e)
-#pragma warning restore 168, IDE0059
+ catch (Exception e) when (e.IsException())
{
}
}
@@ -489,7 +487,7 @@ public RandomAcceptedStrings(Automaton a)
public int[] GetRandomAcceptedString(Random r)
{
- IList soFar = new List();
+ List soFar = new List();
if (a.IsSingleton)
{
// accepts only one
@@ -527,7 +525,7 @@ public int[] GetRandomAcceptedString(Random r)
if (s.numTransitions == 0)
{
- throw new Exception("this automaton has dead states");
+ throw RuntimeException.Create("this automaton has dead states");
}
bool cheat = r.NextBoolean();
@@ -565,7 +563,7 @@ public int[] GetRandomAcceptedString(Random r)
}
}
- return ArrayUtil.ToInt32Array(soFar);
+ return soFar.ToArray(); // LUCENENET: ArrayUtil.ToIntArray() call unnecessary
}
}
}
\ No newline at end of file
diff --git a/src/Lucene.Net.TestFramework/Util/LineFileDocs.cs b/src/Lucene.Net.TestFramework/Util/LineFileDocs.cs
index cdd1356728..f81fe3e6a1 100644
--- a/src/Lucene.Net.TestFramework/Util/LineFileDocs.cs
+++ b/src/Lucene.Net.TestFramework/Util/LineFileDocs.cs
@@ -327,12 +327,12 @@ public virtual Document NextDoc()
int spot = line.IndexOf(SEP);
if (spot == -1)
{
- throw new Exception("line: [" + line + "] is in an invalid format !");
+ throw RuntimeException.Create("line: [" + line + "] is in an invalid format !");
}
int spot2 = line.IndexOf(SEP, 1 + spot);
if (spot2 == -1)
{
- throw new Exception("line: [" + line + "] is in an invalid format !");
+ throw RuntimeException.Create("line: [" + line + "] is in an invalid format !");
}
docState.Body.SetStringValue(line.Substring(1 + spot2, line.Length - (1 + spot2)));
diff --git a/src/Lucene.Net.TestFramework/Util/LuceneTestCase.cs b/src/Lucene.Net.TestFramework/Util/LuceneTestCase.cs
index 3197a3deff..1a3280193c 100644
--- a/src/Lucene.Net.TestFramework/Util/LuceneTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Util/LuceneTestCase.cs
@@ -1351,7 +1351,7 @@ protected static void AssertSaneFieldCaches(string msg)
{
insanity = FieldCacheSanityChecker.CheckSanity(entries);
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsRuntimeException())
{
DumpArray(msg + ": FieldCache", entries, Console.Error);
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
@@ -2120,6 +2120,7 @@ public static CultureInfo CultureForName(string localeName) // LUCENENET specifi
private static Directory NewFSDirectoryImpl(Type clazz, DirectoryInfo file)
{
return CommandLineUtil.NewFSDirectory(clazz, file);
+ // LUCENENET: No sense in catching just to rethrow again as the same type
}
private static Directory NewDirectoryImpl(Random random, string clazzName)
@@ -2143,7 +2144,7 @@ private static Directory NewDirectoryImpl(Random random, string clazzName)
Type clazz = CommandLineUtil.LoadDirectoryClass(clazzName);
if (clazz == null)
- throw new InvalidOperationException($"Type '{clazzName}' could not be instantiated.");
+ throw IllegalStateException.Create($"Type '{clazzName}' could not be instantiated."); // LUCENENET: We don't get an exception in this case, so throwing one for compatibility
// If it is a FSDirectory type, try its ctor(File)
if (typeof(FSDirectory).IsAssignableFrom(clazz))
{
@@ -2405,6 +2406,7 @@ public static IndexSearcher NewSearcher(LuceneTestCase luceneTestCase, IndexRead
{
if (maybeWrap)
{
+ // LUCENENET: Rethrow.rethrow() call not needed here because it simply rethrows an exception as itself
r = MaybeWrapReader(r);
}
// TODO: this whole check is a coverage hack, we should move it to tests for various filterreaders.
@@ -2413,6 +2415,8 @@ public static IndexSearcher NewSearcher(LuceneTestCase luceneTestCase, IndexRead
{
// TODO: not useful to check DirectoryReader (redundant with checkindex)
// but maybe sometimes run this on the other crazy readers maybeWrapReader creates?
+
+ // LUCENENET: Rethrow.rethrow() call not needed here because it simply rethrows an exception as itself
TestUtil.CheckReader(r);
}
IndexSearcher ret;
@@ -2485,7 +2489,7 @@ protected virtual Stream GetDataFile(string name)
{
return this.GetType().getResourceAsStream(name);
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
throw new IOException("Cannot find resource: " + name, e); // LUCENENET specific - wrapped inner exception
}
@@ -2970,7 +2974,7 @@ private void AssertTermsSeekingEquals(string info, Terms leftTerms, Terms rightT
break;
default:
- throw new InvalidOperationException();
+ throw AssertionError.Create();
}
}
}
@@ -3329,18 +3333,7 @@ public static bool SlowFileExists(Directory dir, string fileName)
dir.OpenInput(fileName, IOContext.DEFAULT).Dispose();
return true;
}
- catch (FileNotFoundException)
- {
- return false;
- }
- // LUCENENET specific - .NET (thankfully) only has one FileNotFoundException, so we don't need this
- //catch (NoSuchFileException)
- //{
- // return false;
- //}
- // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException
- // in Lucene, we need to catch it here to be on the safe side.
- catch (DirectoryNotFoundException)
+ catch (Exception e) when (e.IsNoSuchFileExceptionOrFileNotFoundException())
{
return false;
}
@@ -3385,7 +3378,7 @@ public static bool SlowFileExists(Directory dir, string fileName)
//// {
//// if (attempt++ >= TEMP_NAME_RETRY_THRESHOLD)
//// {
- //// throw new Exception("Failed to get a temporary name too many times, check your temp directory and consider manually cleaning it: " + directory.FullName);
+ //// throw RuntimeException.Create("Failed to get a temporary name too many times, check your temp directory and consider manually cleaning it: " + directory.FullName);
//// }
//// f = new DirectoryInfo(Path.Combine(directory.FullName, prefix + "-" + ctx.RunnerSeed + "-" + string.Format(CultureInfo.InvariantCulture, "%03d", attempt)));
@@ -3393,7 +3386,7 @@ public static bool SlowFileExists(Directory dir, string fileName)
//// {
//// f.Create();
//// }
- //// catch (IOException)
+ //// catch (Exception ioe) when (ioe.IsIOException())
//// {
//// iterate = false;
//// }
@@ -3434,7 +3427,7 @@ public static DirectoryInfo CreateTempDir(string prefix)
{
if (attempt++ >= TEMP_NAME_RETRY_THRESHOLD)
{
- throw new Exception("Failed to get a temporary name too many times, check your temp directory and consider manually cleaning it: " + System.IO.Path.GetTempPath());
+ throw RuntimeException.Create("Failed to get a temporary name too many times, check your temp directory and consider manually cleaning it: " + System.IO.Path.GetTempPath());
}
// LUCENENET specific - need to use a random file name instead of a sequential one or two threads may attempt to do
// two operations on a file at the same time.
@@ -3449,9 +3442,7 @@ public static DirectoryInfo CreateTempDir(string prefix)
iterate = false;
}
}
-#pragma warning disable 168, IDE0059
- catch (IOException exc)
-#pragma warning restore 168, IDE0059
+ catch (Exception exc) when (exc.IsIOException())
{
iterate = true;
}
@@ -3479,7 +3470,7 @@ public static FileInfo CreateTempFile(string prefix, string suffix)
//{
// if (attempt++ >= TEMP_NAME_RETRY_THRESHOLD)
// {
- // throw new Exception("Failed to get a temporary name too many times, check your temp directory and consider manually cleaning it: " + System.IO.Path.GetTempPath());
+ // throw RuntimeException.Create("Failed to get a temporary name too many times, check your temp directory and consider manually cleaning it: " + System.IO.Path.GetTempPath());
// }
// //f = new FileInfo(Path.Combine(System.IO.Path.GetTempPath(), prefix + "-" + string.Format(CultureInfo.InvariantCulture, "{0:D3}", attempt) + suffix));
// f = FileSupport.CreateTempFile(prefix, suffix, new DirectoryInfo(System.IO.Path.GetTempPath()));
@@ -3560,18 +3551,7 @@ private static void CleanupTemporaryFiles()
{
TestUtil.Rm(everything);
}
- // LUCENENET specific: UnauthorizedAccessException doesn't subclass IOException as
- // AccessDeniedException does in Java, so we need a special case for it.
- catch (UnauthorizedAccessException e)
- {
- // Type suiteClass = RandomizedContext.Current.GetTargetType;
- // if (suiteClass.IsAnnotationPresent(typeof(SuppressTempFileChecks)))
- // {
- Console.Error.WriteLine("WARNING: Leftover undeleted temporary files " + e.Message);
- return;
- // }
- }
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
// Type suiteClass = RandomizedContext.Current.GetTargetType;
// if (suiteClass.IsAnnotationPresent(typeof(SuppressTempFileChecks)))
diff --git a/src/Lucene.Net.TestFramework/Util/RemoveUponClose.cs b/src/Lucene.Net.TestFramework/Util/RemoveUponClose.cs
index 37cc3f9a5e..a992b8e148 100644
--- a/src/Lucene.Net.TestFramework/Util/RemoveUponClose.cs
+++ b/src/Lucene.Net.TestFramework/Util/RemoveUponClose.cs
@@ -1,4 +1,4 @@
-#if TESTFRAMEWORK
+#if TESTFRAMEWORK
// LUCENENET NOTE: This is incomplete
using System;
@@ -61,7 +61,7 @@ public void Dispose()
{
TestUtil.Rm(file);
}
- catch (IOException e)
+ catch (Exception e) when (e.IsIOException())
{
throw new IOException("Could not remove temporary location '" + file.FullName + "', created at stack trace:\n" + CreationStack, e);
}
diff --git a/src/Lucene.Net.TestFramework/Util/TestRuleStoreClassName.cs b/src/Lucene.Net.TestFramework/Util/TestRuleStoreClassName.cs
index 0c7e5cdf48..66e7698a57 100644
--- a/src/Lucene.Net.TestFramework/Util/TestRuleStoreClassName.cs
+++ b/src/Lucene.Net.TestFramework/Util/TestRuleStoreClassName.cs
@@ -1,4 +1,4 @@
-#if TESTFRAMEWORK
+#if TESTFRAMEWORK
// LUCENENET NOTE: This is incomplete
using System;
@@ -82,7 +82,7 @@ public virtual Type TestClass
Description localDescription = Description;
if (localDescription == null)
{
- throw new Exception("The rule is not currently executing.");
+ throw RuntimeException.Create("The rule is not currently executing.");
}
return localDescription.TestClass;
}
diff --git a/src/Lucene.Net.TestFramework/Util/TestUtil.cs b/src/Lucene.Net.TestFramework/Util/TestUtil.cs
index 7d671c2446..2d880b967d 100644
--- a/src/Lucene.Net.TestFramework/Util/TestUtil.cs
+++ b/src/Lucene.Net.TestFramework/Util/TestUtil.cs
@@ -186,7 +186,7 @@ public static CheckIndex.Status CheckIndex(Directory dir, bool crossCheckTermVec
Console.WriteLine("CheckIndex failed");
checker.FlushInfoStream();
Console.WriteLine(bos.ToString());
- throw new Exception("CheckIndex failed");
+ throw RuntimeException.Create("CheckIndex failed");
}
else
{
@@ -228,7 +228,7 @@ public static void CheckReader(AtomicReader reader, bool crossCheckTermVectors)
Console.WriteLine("CheckReader failed");
infoStream.Flush();
Console.WriteLine(bos.ToString());
- throw new Exception("CheckReader failed");
+ throw RuntimeException.Create("CheckReader failed");
}
else
{
@@ -737,7 +737,7 @@ public static Document CloneDocument(Document doc1)
break;
default:
- throw new InvalidOperationException("unknown Type: " + dvType);
+ throw IllegalStateException.Create("unknown Type: " + dvType);
}
}
else if (numType != NumericType.NONE)
@@ -761,7 +761,7 @@ public static Document CloneDocument(Document doc1)
break;
default:
- throw new InvalidOperationException("unknown Type: " + numType);
+ throw IllegalStateException.Create("unknown Type: " + numType);
}
}
else
@@ -867,7 +867,7 @@ public static ICharSequence BytesToCharSequence(BytesRef @ref, Random random)
// ex.shutdown();
// ex.awaitTermination(1, TimeUnit.SECONDS);
// }
- // catch (ThreadInterruptedException e)
+ // catch (Exception e) when (e.IsInterruptedException())
// {
// // Just report it on the syserr.
// Console.Error.WriteLine("Could not properly shutdown executor service.");
diff --git a/src/Lucene.Net.Tests.AllProjects/Lucene.Net.Tests.AllProjects.csproj b/src/Lucene.Net.Tests.AllProjects/Lucene.Net.Tests.AllProjects.csproj
new file mode 100644
index 0000000000..ce78dd65b1
--- /dev/null
+++ b/src/Lucene.Net.Tests.AllProjects/Lucene.Net.Tests.AllProjects.csproj
@@ -0,0 +1,73 @@
+
+
+
+
+
+
+
+
+ Lucene.Net.Tests.AllProjects
+ Lucene.Net
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ar/TestArabicFilters.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ar/TestArabicFilters.cs
index a17c32a4fa..1e51208f07 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ar/TestArabicFilters.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ar/TestArabicFilters.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -86,7 +86,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("ArabicNormalization", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
@@ -96,7 +96,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("Arabicstem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
@@ -106,7 +106,7 @@ public virtual void TestBogusArguments()
CharFilterFactory("Persian", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
@@ -116,7 +116,7 @@ public virtual void TestBogusArguments()
TokenizerFactory("ArabicLetter", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Bg/TestBulgarianStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Bg/TestBulgarianStemFilterFactory.cs
index 1ddc97838c..ac3044adac 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Bg/TestBulgarianStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Bg/TestBulgarianStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -50,7 +50,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("BulgarianStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Br/TestBrazilianStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Br/TestBrazilianStemFilterFactory.cs
index 1283f974e8..dee0ebf581 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Br/TestBrazilianStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Br/TestBrazilianStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -50,7 +50,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("BrazilianStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/CharFilters/HTMLStripCharFilterTest.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/CharFilters/HTMLStripCharFilterTest.cs
index 8c18fd7035..38a612e233 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/CharFilters/HTMLStripCharFilterTest.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/CharFilters/HTMLStripCharFilterTest.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1 (added fix for SOLR-5983: HTMLStripCharFilter is treating CDATA sections incorrectly)
using J2N.Text;
using Lucene.Net.Util;
using NUnit.Framework;
@@ -27,7 +27,6 @@ namespace Lucene.Net.Analysis.CharFilters
* limitations under the License.
*/
- // LUCENENET NOTE: Version compatibility level 4.8.1 (added fix for SOLR-5983: HTMLStripCharFilter is treating CDATA sections incorrectly)
public class HTMLStripCharFilterTest : BaseTokenStreamTestCase
{
@@ -710,7 +709,7 @@ public static void AssertHTMLStripsTo(TextReader input, string gold, ISet throw new NotSupportedException("IsMarkSupported");
+ public override bool IsMarkSupported => throw UnsupportedOperationException.Create("IsMarkSupported");
public override int Read()
{
- throw new NotSupportedException("Read()");
+ throw UnsupportedOperationException.Create("Read()");
}
// LUCENENET: We don't support these overloads in .NET
// public override int Read(char[] cbuf)
// {
- //throw new NotSupportedException("Read(char[])");
+ //throw UnsupportedOperationException.Create("Read(char[])");
// }
//public override int read(CharBuffer target)
//{
- // throw new NotSupportedException("Read(CharBuffer)");
+ // throw UnsupportedOperationException.Create("Read(CharBuffer)");
//}
- public override bool IsReady => throw new NotSupportedException("Ready()");
+ public override bool IsReady => throw UnsupportedOperationException.Create("Ready()");
public override void Reset()
{
- throw new NotSupportedException("Reset()");
+ throw UnsupportedOperationException.Create("Reset()");
}
public override long Skip(int n)
{
- throw new NotSupportedException("Skip(long)");
+ throw UnsupportedOperationException.Create("Skip(long)");
}
protected override int Correct(int currentOff)
{
- throw new NotSupportedException("Correct(int)");
+ throw UnsupportedOperationException.Create("Correct(int)");
}
protected override void Dispose(bool disposing)
{
- throw new NotSupportedException("Close()");
+ throw UnsupportedOperationException.Create("Close()");
}
public override int Read(char[] arg0, int arg1, int arg2)
{
- throw new NotSupportedException("Read(char[], int, int)");
+ throw UnsupportedOperationException.Create("Read(char[], int, int)");
}
}
@@ -131,7 +131,7 @@ public virtual void TestWrapping()
cs.Mark(1);
fail();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
assertEquals("Mark(int)", e.Message);
}
@@ -141,7 +141,7 @@ public virtual void TestWrapping()
var supported = cs.IsMarkSupported;
fail();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
assertEquals("IsMarkSupported", e.Message);
}
@@ -151,7 +151,7 @@ public virtual void TestWrapping()
cs.Read();
fail();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
assertEquals("Read()", e.Message);
}
@@ -161,7 +161,7 @@ public virtual void TestWrapping()
cs.read(new char[0]);
fail();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
// LUCENENET NOTE: TextReader doesn't support an overload that doesn't supply
// index and count. We have an extension method that does in test environment,
@@ -177,7 +177,7 @@ public virtual void TestWrapping()
// cs.read(CharBuffer.wrap(new char[0]));
// fail();
//}
- //catch (Exception e)
+ //catch (Exception e) when (e.IsException())
//{
// assertEquals("Read(CharBuffer)", e.Message);
//}
@@ -187,7 +187,7 @@ public virtual void TestWrapping()
cs.Reset();
fail();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
assertEquals("Reset()", e.Message);
}
@@ -197,7 +197,7 @@ public virtual void TestWrapping()
cs.Skip(1);
fail();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
assertEquals("Skip(long)", e.Message);
}
@@ -207,7 +207,7 @@ public virtual void TestWrapping()
cs.CorrectOffset(1);
fail();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
assertEquals("Correct(int)", e.Message);
}
@@ -217,7 +217,7 @@ public virtual void TestWrapping()
cs.Dispose();
fail();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
assertEquals("Close()", e.Message);
}
@@ -227,7 +227,7 @@ public virtual void TestWrapping()
cs.Read(new char[0], 0, 0);
fail();
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
assertEquals("Read(char[], int, int)", e.Message);
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestFactories.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestFactories.cs
index 9647c42fa8..d8c521b4f4 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestFactories.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestFactories.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
@@ -142,9 +142,9 @@ private static AbstractAnalysisFactory Initialize(Type factoryClazz) // LUCENENE
{
ctor = factoryClazz.GetConstructor(new Type[] { typeof(IDictionary) });
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception("factory '" + factoryClazz + "' does not have a proper ctor!", e);
+ throw RuntimeException.Create("factory '" + factoryClazz + "' does not have a proper ctor!", e);
}
AbstractAnalysisFactory factory = null;
@@ -152,15 +152,15 @@ private static AbstractAnalysisFactory Initialize(Type factoryClazz) // LUCENENE
{
factory = (AbstractAnalysisFactory)ctor.Invoke(new object[] { args });
}
- catch (TypeInitializationException e)
+ catch (Exception e) when (e.IsInstantiationException())
{
- throw new Exception(e.Message, e);
+ throw RuntimeException.Create(e);
}
- catch (MethodAccessException e)
+ catch (Exception e) when (e.IsIllegalAccessException())
{
- throw new Exception(e.Message, e);
+ throw RuntimeException.Create(e);
}
- catch (TargetInvocationException e)
+ catch (Exception e) when (e.IsInvocationTargetException())
{
if (e.InnerException is ArgumentException)
{
@@ -175,16 +175,14 @@ private static AbstractAnalysisFactory Initialize(Type factoryClazz) // LUCENENE
{
aware.Inform(new StringMockResourceLoader(""));
}
-#pragma warning disable CA1031 // Do not catch general exception types
- catch (IOException)
+ catch (Exception ignored) when (ignored.IsIOException())
{
// its ok if the right files arent available or whatever to throw this
}
- catch (ArgumentException)
+ catch (Exception ignored) when (ignored.IsIllegalArgumentException())
{
// is this ok? I guess so
}
-#pragma warning restore CA1031 // Do not catch general exception types
}
return factory;
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestRandomChains.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestRandomChains.cs
index 42584348e5..acf341a1ba 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestRandomChains.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestRandomChains.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using J2N.Runtime.CompilerServices;
using J2N.Text;
@@ -117,9 +117,9 @@ static TestRandomChains()
}
}
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception(e.Message, e);
+ throw Error.Create(e);
}
try
{
@@ -145,9 +145,9 @@ static TestRandomChains()
}
}
}
- catch (Exception e)
+ catch (Exception e) when (e.IsException())
{
- throw new Exception(e.Message, e);
+ throw Error.Create(e);
}
allowedTokenizerArgs = new JCG.HashSet(IdentityEqualityComparer.Default);
@@ -509,7 +509,7 @@ public object Create(Random random)
{
return new Dictionary(affixStream, dictStream);
}
- catch (Exception /*ex*/)
+ catch (Exception ex) when (ex.IsException())
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
#pragma warning disable 162
@@ -554,7 +554,7 @@ public object Create(Random random)
HyphenationTree hyphenator = HyphenationCompoundWordTokenFilter.GetHyphenationTree(@is);
return hyphenator;
}
- catch (Exception /*ex*/)
+ catch (Exception ex) when (ex.IsException())
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
#pragma warning disable 162
@@ -574,7 +574,7 @@ public object Create(Random random)
Type clazz = Type.GetType("Lucene.Net.Tartarus.Snowball.Ext." + lang + "Stemmer, Lucene.Net.Analysis.Common");
return clazz.GetConstructor(new Type[0]).Invoke(new object[0]);
}
- catch (Exception /*ex*/)
+ catch (Exception ex) when (ex.IsException())
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
#pragma warning disable 162
@@ -680,7 +680,7 @@ public object Create(Random random)
{
return builder.Build();
}
- catch (Exception /*ex*/)
+ catch (Exception ex) when (ex.IsException())
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
#pragma warning disable 162
@@ -704,7 +704,7 @@ public object Create(Random random)
{
return b.Build();
}
- catch (Exception /*ex*/)
+ catch (Exception ex) when (ex.IsException())
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
#pragma warning disable 162
@@ -891,7 +891,7 @@ private T CreateComponent(ConstructorInfo ctor, object[] args, StringBuilder
descr.append("(").append(@params).append(")");
return instance;
}
- catch (TargetInvocationException ite)
+ catch (Exception ite) when (ite.IsInvocationTargetException())
{
if (ite.InnerException != null && (ite.InnerException.GetType().Equals(typeof(ArgumentException))
|| ite.InnerException.GetType().Equals(typeof(ArgumentOutOfRangeException))
@@ -910,13 +910,15 @@ private T CreateComponent(ConstructorInfo ctor, object[] args, StringBuilder
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
}
- //catch (IllegalAccessException iae)
+ // LUCENENET: These are not necessary because all they do is catch and re-throw as an "unchecked"
+ // exception type, which .NET doesn't care about. Just let them propagate instead of catching.
+ //catch (Exception iae) when (iae.IsIllegalAccessException())
//{
- // Rethrow.rethrow(iae);
+ // throw;
//}
- //catch (InstantiationException ie)
+ //catch (Exception ie) when (ie.IsInstantiationException())
//{
- // Rethrow.rethrow(ie);
+ // throw;
//}
return default; // no success
}
@@ -1135,7 +1137,7 @@ public void TestRandomChains_()
CheckRandomData(random, a, 500 * RandomMultiplier, 20, false,
false /* We already validate our own offsets... */);
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsThrowable())
{
Console.WriteLine("Exception from random analyzer: " + a);
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
@@ -1163,7 +1165,7 @@ public void TestRandomChainsWithLargeStrings()
CheckRandomData(random, a, 50 * RandomMultiplier, 128, false,
false /* We already validate our own offsets... */);
}
- catch (Exception /*e*/)
+ catch (Exception e) when (e.IsThrowable())
{
Console.WriteLine("Exception from random analyzer: " + a);
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestStopFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestStopFilterFactory.cs
index 55b31d594e..9c8dd8e404 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestStopFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestStopFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -69,7 +69,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("Stop", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
@@ -85,7 +85,7 @@ public virtual void TestBogusFormats()
TokenFilterFactory("Stop", "words", "stop-snowball.txt", "format", "bogus");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
string msg = expected.Message;
assertTrue(msg, msg.Contains("Unknown"));
@@ -98,7 +98,7 @@ public virtual void TestBogusFormats()
// implicit default words file
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
string msg = expected.Message;
assertTrue(msg, msg.Contains("can not be specified"));
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestTypeTokenFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestTypeTokenFilterFactory.cs
index 9ed57938f4..759f114f0f 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestTypeTokenFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestTypeTokenFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -71,7 +71,7 @@ public virtual void TestMissingTypesParameter()
TokenFilterFactory("Type", "enablePositionIncrements", "false");
fail("not supplying 'types' parameter should cause an IllegalArgumentException");
}
- catch (ArgumentException)
+ catch (Exception e) when (e.IsIllegalArgumentException())
{
// everything ok
}
@@ -87,7 +87,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("Type", "types", "stoptypes-1.txt", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Cz/TestCzechStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Cz/TestCzechStemFilterFactory.cs
index d584b97c78..a91c19047a 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Cz/TestCzechStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Cz/TestCzechStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -50,7 +50,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("CzechStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanLightStemFilterFactory.cs
index 86864074db..77a34dc6c0 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanLightStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanLightStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("GermanLightStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanMinimalStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanMinimalStemFilterFactory.cs
index 4409f29101..f13f33dcb9 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanMinimalStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanMinimalStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("GermanMinimalStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanNormalizationFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanNormalizationFilterFactory.cs
index 343d9c9232..67b5bbfc5d 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanNormalizationFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanNormalizationFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("GermanNormalization", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanStemFilterFactory.cs
index 0db1e64148..9c84f113fc 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/De/TestGermanStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -50,7 +50,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("GermanStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/El/TestGreekLowerCaseFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/El/TestGreekLowerCaseFilterFactory.cs
index 9034ca41f7..8df46133c8 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/El/TestGreekLowerCaseFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/El/TestGreekLowerCaseFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -50,7 +50,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("GreekLowerCase", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/El/TestGreekStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/El/TestGreekStemFilterFactory.cs
index 117cdcde98..daaa67e306 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/El/TestGreekStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/El/TestGreekStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -48,7 +48,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("GreekStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestEnglishMinimalStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestEnglishMinimalStemFilterFactory.cs
index 26563f71a0..7153351ac1 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestEnglishMinimalStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestEnglishMinimalStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("EnglishMinimalStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestKStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestKStemFilterFactory.cs
index 7ad473a0e5..d9ff0e473e 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestKStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestKStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("KStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestPorterStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestPorterStemFilterFactory.cs
index 986c4e2971..4542a275e0 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestPorterStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/En/TestPorterStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -50,7 +50,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("PorterStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Es/TestSpanishLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Es/TestSpanishLightStemFilterFactory.cs
index 7f69ba239c..dfc1415b22 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Es/TestSpanishLightStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Es/TestSpanishLightStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("SpanishLightStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fa/TestPersianNormalizationFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fa/TestPersianNormalizationFilterFactory.cs
index 523b1984ba..57b7c19d03 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fa/TestPersianNormalizationFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fa/TestPersianNormalizationFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -50,7 +50,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("PersianNormalization", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fi/TestFinnishLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fi/TestFinnishLightStemFilterFactory.cs
index 10e3ac9e00..4a21c43b90 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fi/TestFinnishLightStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fi/TestFinnishLightStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("FinnishLightStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fr/TestFrenchLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fr/TestFrenchLightStemFilterFactory.cs
index 02814da72d..92b1668fd4 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fr/TestFrenchLightStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fr/TestFrenchLightStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -50,7 +50,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("FrenchLightStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fr/TestFrenchMinimalStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fr/TestFrenchMinimalStemFilterFactory.cs
index b9a37e1629..e48a0aa774 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fr/TestFrenchMinimalStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Fr/TestFrenchMinimalStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("FrenchMinimalStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ga/TestIrishLowerCaseFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ga/TestIrishLowerCaseFilterFactory.cs
index a3e4ba582a..156ce84cb3 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ga/TestIrishLowerCaseFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ga/TestIrishLowerCaseFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("IrishLowerCase", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Gl/TestGalicianMinimalStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Gl/TestGalicianMinimalStemFilterFactory.cs
index 7a0f8e2f1d..ea6c9ae612 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Gl/TestGalicianMinimalStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Gl/TestGalicianMinimalStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("GalicianMinimalStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Gl/TestGalicianStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Gl/TestGalicianStemFilterFactory.cs
index 39ef0e2b69..1c389d9854 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Gl/TestGalicianStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Gl/TestGalicianStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("GalicianStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hi/TestHindiFilters.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hi/TestHindiFilters.cs
index 1d6b1613b1..5e75521937 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hi/TestHindiFilters.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hi/TestHindiFilters.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -77,7 +77,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("IndicNormalization", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
@@ -87,7 +87,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("HindiNormalization", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
@@ -97,7 +97,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("HindiStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hu/TestHungarianLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hu/TestHungarianLightStemFilterFactory.cs
index b7b5236538..f9ab107c36 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hu/TestHungarianLightStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hu/TestHungarianLightStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("HungarianLightStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hunspell/TestDictionary.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hunspell/TestDictionary.cs
index 4b85b2d0a2..206c023ff8 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hunspell/TestDictionary.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hunspell/TestDictionary.cs
@@ -110,7 +110,7 @@ public virtual void TestInvalidData()
new Dictionary(affixStream, dictStream);
fail("didn't get expected exception");
}
- catch (Exception expected)
+ catch (Exception expected) when (expected.IsParseException())
{
assertTrue(expected.Message.StartsWith("The affix file contains a rule with less than four elements", StringComparison.Ordinal));
//assertEquals(24, expected.ErrorOffset); // No parse exception in LUCENENET
@@ -128,7 +128,7 @@ public virtual void TestInvalidFlags()
new Dictionary(affixStream, dictStream);
fail("didn't get expected exception");
}
- catch (Exception expected)
+ catch (Exception expected) when (expected.IsException())
{
assertTrue(expected.Message.StartsWith("expected only one flag", StringComparison.Ordinal));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hunspell/TestHunspellStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hunspell/TestHunspellStemFilterFactory.cs
index 2171e02be8..b0d8e8009b 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hunspell/TestHunspellStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Hunspell/TestHunspellStemFilterFactory.cs
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("HunspellStem", "dictionary", "simple.dic", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Id/TestIndonesianStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Id/TestIndonesianStemFilterFactory.cs
index f1b9d827b1..4dd3db8c56 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Id/TestIndonesianStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Id/TestIndonesianStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -62,7 +62,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("IndonesianStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/It/TestItalianLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/It/TestItalianLightStemFilterFactory.cs
index a17a4b5554..eee010f776 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/It/TestItalianLightStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/It/TestItalianLightStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("ItalianLightStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Lv/TestLatvianStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Lv/TestLatvianStemFilterFactory.cs
index 1f2af4f11b..3966dac80e 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Lv/TestLatvianStemFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Lv/TestLatvianStemFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -47,7 +47,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("LatvianStem", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/PatternAnalyzerTest.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/PatternAnalyzerTest.cs
index b6a164fee3..8f09e8e23b 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/PatternAnalyzerTest.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/PatternAnalyzerTest.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Support;
using NUnit.Framework;
@@ -137,6 +137,8 @@ private void Check(PatternAnalyzer analyzer, string document, string[] expected)
[Test]
public virtual void TestRandomStrings()
{
+ // LUCENENET: Removed code dealing with buggy JRE
+
Analyzer a = new PatternAnalyzer(TEST_VERSION_CURRENT, new Regex(",", RegexOptions.Compiled), true, StopAnalyzer.ENGLISH_STOP_WORDS_SET);
CheckRandomData(Random, a, 10000 * RandomMultiplier);
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestCapitalizationFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestCapitalizationFilterFactory.cs
index bdbe4efa92..57c4e17fa7 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestCapitalizationFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestCapitalizationFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -258,7 +258,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("Capitalization", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
@@ -280,7 +280,7 @@ public virtual void TestInvalidArguments()
TokenFilterFactory("Capitalization", "keep", "and the it BIG", "onlyFirstWord", "false", arg, "-3", "okPrefix", "McK", "forceFirstLetter", "true").Create(stream);
fail();
}
- catch (ArgumentException expected)
+ catch (ArgumentOutOfRangeException expected) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
{
assertTrue(expected.Message.Contains(arg + " must be greater than or equal to zero") || expected.Message.Contains(arg + " must be greater than zero"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestCodepointCountFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestCodepointCountFilterFactory.cs
index b410cfc573..ca1e110856 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestCodepointCountFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestCodepointCountFilterFactory.cs
@@ -45,7 +45,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("CodepointCount", "min", "4", "max", "5", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
@@ -63,7 +63,7 @@ public virtual void TestInvalidArguments()
TokenFilterFactory("CodepointCount", CodepointCountFilterFactory.MIN_KEY, "5", CodepointCountFilterFactory.MAX_KEY, "4").Create(stream);
fail();
}
- catch (ArgumentException expected)
+ catch (ArgumentOutOfRangeException expected) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
{
assertTrue(expected.Message.Contains("maximum length must not be greater than minimum length"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestKeepFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestKeepFilterFactory.cs
index ecc0f359ad..220e6b8a8d 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestKeepFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestKeepFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -51,7 +51,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("KeepWord", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestKeywordMarkerFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestKeywordMarkerFilterFactory.cs
index be36b64415..91703de47d 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestKeywordMarkerFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestKeywordMarkerFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -100,7 +100,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("KeywordMarker", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLengthFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLengthFilterFactory.cs
index 5e7aad226e..96b7266742 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLengthFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLengthFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
using NUnit.Framework;
@@ -59,7 +59,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("Length", LengthFilterFactory.MIN_KEY, "4", LengthFilterFactory.MAX_KEY, "5", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
@@ -77,7 +77,7 @@ public virtual void TestInvalidArguments()
TokenFilterFactory("Length", LengthFilterFactory.MIN_KEY, "5", LengthFilterFactory.MAX_KEY, "4").Create(stream);
fail();
}
- catch (ArgumentException expected)
+ catch (ArgumentOutOfRangeException expected) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
{
assertTrue(expected.Message.Contains("maximum length must not be greater than minimum length"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenCountFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenCountFilterFactory.cs
index f9a818ee8c..75cbdeadc3 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenCountFilterFactory.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenCountFilterFactory.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System;
@@ -49,7 +49,7 @@ public virtual void TestRequired()
TokenFilterFactory("LimitTokenCount");
fail();
}
- catch (ArgumentException e)
+ catch (Exception e) when (e.IsIllegalArgumentException())
{
assertTrue("exception doesn't mention param: " + e.Message, 0 < e.Message.IndexOf(LimitTokenCountFilterFactory.MAX_TOKEN_COUNT_KEY, StringComparison.Ordinal));
}
@@ -66,7 +66,7 @@ public virtual void TestBogusArguments()
TokenFilterFactory("LimitTokenCount", LimitTokenCountFilterFactory.MAX_TOKEN_COUNT_KEY, "3", "bogusArg", "bogusValue");
fail();
}
- catch (ArgumentException expected)
+ catch (Exception expected) when (expected.IsIllegalArgumentException())
{
assertTrue(expected.Message.Contains("Unknown parameters"));
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenPositionFilter.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenPositionFilter.cs
index 596986b4fb..e46e0fbf1b 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenPositionFilter.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenPositionFilter.cs
@@ -1,4 +1,4 @@
-// Lucene version compatibility level 4.8.1
+// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Synonym;
using Lucene.Net.Util;
using NUnit.Framework;
@@ -82,7 +82,8 @@ public virtual void TestMaxPosition3WithSynomyms()
[Test]
public virtual void TestIllegalArguments()
{
- Assert.Throws(() => new LimitTokenPositionFilter(new MockTokenizer(new StringReader("one two three four five")), 0));
+ // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
+ Assert.Throws