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 qs, Analyzer a) } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - Console.WriteLine(e.ToString()); + Console.Error.WriteLine(e.ToString()); } } diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/FileBasedQueryMaker.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/FileBasedQueryMaker.cs index a97ebf66b9..ad941169c2 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Feeds/FileBasedQueryMaker.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/FileBasedQueryMaker.cs @@ -96,7 +96,7 @@ protected override Query[] PrepareQueries() { qq.Add(qp.Parse(line)); } - catch (ParseException e) + catch (Lucene.Net.QueryParsers.Classic.ParseException e) { Console.Error.WriteLine("Exception: " + e.Message + " occurred while parsing line: " + lineNum + " Text: " + line); } diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/LineDocSource.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/LineDocSource.cs index e3d2f0f7f9..17a821e435 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Feeds/LineDocSource.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/LineDocSource.cs @@ -64,9 +64,9 @@ private void OpenFile() reader.ReadLine(); // skip one line - the header line - already handled that info } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } @@ -141,9 +141,9 @@ private LineParser CreateDocDataLineReader(string line) Type clazz = Type.GetType(docDataLineReaderClassName); return (LineParser)Activator.CreateInstance(clazz, (object)header); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception("Failed to instantiate " + docDataLineReaderClassName, e); + throw RuntimeException.Create("Failed to instantiate " + docDataLineReaderClassName, e); } } @@ -215,21 +215,21 @@ public override void ParseLine(DocData docData, string line) int k2 = line.IndexOf(WriteLineDocTask.SEP, k1); if (k2 < 0) { - throw new Exception("line: [" + line + "] is in an invalid format (missing: separator title::date)!"); + throw RuntimeException.Create("line: [" + line + "] is in an invalid format (missing: separator title::date)!"); } docData.Title = line.Substring(k1, k2 - k1); k1 = k2 + 1; k2 = line.IndexOf(WriteLineDocTask.SEP, k1); if (k2 < 0) { - throw new Exception("line: [" + line + "] is in an invalid format (missing: separator date::body)!"); + throw RuntimeException.Create("line: [" + line + "] is in an invalid format (missing: separator date::body)!"); } docData.SetDate(line.Substring(k1, k2 - k1)); k1 = k2 + 1; k2 = line.IndexOf(WriteLineDocTask.SEP, k1); if (k2 >= 0) { - throw new Exception("line: [" + line + "] is in an invalid format (too many separators)!"); + throw RuntimeException.Create("line: [" + line + "] is in an invalid format (too many separators)!"); } // last one docData.Body = line.Substring(k1); @@ -284,7 +284,7 @@ public override void ParseLine(DocData docData, string line) { if (n >= m_header.Length) { - throw new Exception("input line has invalid format: " + (n + 1) + " fields instead of " + m_header.Length + " :: [" + line + "]"); + throw RuntimeException.Create("input line has invalid format: " + (n + 1) + " fields instead of " + m_header.Length + " :: [" + line + "]"); } SetDocDataField(docData, n, line.Substring(k1, k2 - k1)); ++n; @@ -292,7 +292,7 @@ public override void ParseLine(DocData docData, string line) } if (n != m_header.Length - 1) { - throw new Exception("input line has invalid format: " + (n + 1) + " fields instead of " + m_header.Length + " :: [" + line + "]"); + throw RuntimeException.Create("input line has invalid format: " + (n + 1) + " fields instead of " + m_header.Length + " :: [" + line + "]"); } // last one SetDocDataField(docData, n, line.Substring(k1)); diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/LongToEnglishQueryMaker.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/LongToEnglishQueryMaker.cs index 42f4a5ce7a..78580dbc65 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Feeds/LongToEnglishQueryMaker.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/LongToEnglishQueryMaker.cs @@ -42,7 +42,7 @@ public class Int64ToEnglishQueryMaker : IQueryMaker public virtual Query MakeQuery(int size) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public virtual Query MakeQuery() diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/RandomFacetSource.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/RandomFacetSource.cs index b9565703fe..467180c2a3 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Feeds/RandomFacetSource.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/RandomFacetSource.cs @@ -101,7 +101,7 @@ public override void SetConfig(Config config) maxFacetDepth = config.Get("max.facet.depth", 3); if (maxFacetDepth < 2) { - throw new ArgumentException("max.facet.depth must be at least 2; got: " + maxFacetDepth); + throw new ArgumentOutOfRangeException("max.facet.depth", "max.facet.depth must be at least 2; got: " + maxFacetDepth); } maxValue = maxDocFacets * maxFacetDepth; } diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/ReutersContentSource.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/ReutersContentSource.cs index e7f38f73f6..51815d908d 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Feeds/ReutersContentSource.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/ReutersContentSource.cs @@ -53,7 +53,7 @@ public override void SetConfig(Config config) CollectFiles(dataDir, inputFiles); if (inputFiles.Count == 0) { - 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/ReutersQueryMaker.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/ReutersQueryMaker.cs index 238979d0a0..126d9b8c6f 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Feeds/ReutersQueryMaker.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/ReutersQueryMaker.cs @@ -101,7 +101,7 @@ private static Query[] CreateQueries(IList qs, Analyzer a) } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { Console.Error.WriteLine(e.ToString()); } diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/SpatialDocMaker.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/SpatialDocMaker.cs index ff3b1bc379..a54aa333c7 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Feeds/SpatialDocMaker.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/SpatialDocMaker.cs @@ -58,7 +58,7 @@ public static SpatialStrategy GetSpatialStrategy(int roundNumber) { if (!spatialStrategyCache.TryGetValue(roundNumber, out SpatialStrategy result) || result == null) { - throw new InvalidOperationException("Strategy should have been init'ed by SpatialDocMaker by now"); + throw IllegalStateException.Create("Strategy should have been init'ed by SpatialDocMaker by now"); } return result; } @@ -73,7 +73,7 @@ protected virtual SpatialStrategy MakeSpatialStrategy(Config config) // LUCENENET: The second argument was ClassLoader in Java, which should be made into // Assembly in .NET. However, Spatial4n currently doesn't support it. - // In .NET it makes more logical sense to make 2 overloads and throw NullReferenceException + // In .NET it makes more logical sense to make 2 overloads and throw ArgumentNullException // if the second argument is null, anyway. So no need to change this once support has been added. // See: https://github.com/NightOwl888/Spatial4n/issues/1 SpatialContext ctx = SpatialContextFactory.MakeSpatialContext(configMap /*, assembly: null*/); @@ -96,7 +96,7 @@ public DictionaryAnonymousClass(Config config) public string this[string key] { get => config.Get("spatial." + key, null); - set => throw new NotSupportedException(); + set => throw UnsupportedOperationException.Create(); } public bool TryGetValue(string key, out string value) @@ -114,25 +114,25 @@ public bool ContainsKey(string key) #region IDictionary members - ICollection IDictionary.Keys => throw new NotSupportedException(); + ICollection IDictionary.Keys => throw UnsupportedOperationException.Create(); - ICollection IDictionary.Values => throw new NotSupportedException(); + ICollection IDictionary.Values => throw UnsupportedOperationException.Create(); - int ICollection>.Count => throw new NotSupportedException(); + int ICollection>.Count => throw UnsupportedOperationException.Create(); public bool IsReadOnly => true; - void IDictionary.Add(string key, string value) => throw new NotSupportedException(); - void ICollection>.Add(KeyValuePair item) => throw new NotSupportedException(); - void ICollection>.Clear() => throw new NotSupportedException(); - bool ICollection>.Contains(KeyValuePair item) => throw new NotSupportedException(); + void IDictionary.Add(string key, string value) => throw UnsupportedOperationException.Create(); + void ICollection>.Add(KeyValuePair item) => throw UnsupportedOperationException.Create(); + void ICollection>.Clear() => throw UnsupportedOperationException.Create(); + bool ICollection>.Contains(KeyValuePair item) => throw UnsupportedOperationException.Create(); - void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) => throw new NotSupportedException(); - IEnumerator> IEnumerable>.GetEnumerator() => throw new NotSupportedException(); - bool IDictionary.Remove(string key) => throw new NotSupportedException(); - bool ICollection>.Remove(KeyValuePair item) => throw new NotSupportedException(); + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) => throw UnsupportedOperationException.Create(); + IEnumerator> IEnumerable>.GetEnumerator() => throw UnsupportedOperationException.Create(); + bool IDictionary.Remove(string key) => throw UnsupportedOperationException.Create(); + bool ICollection>.Remove(KeyValuePair item) => throw UnsupportedOperationException.Create(); - IEnumerator IEnumerable.GetEnumerator() => throw new NotSupportedException(); + IEnumerator IEnumerable.GetEnumerator() => throw UnsupportedOperationException.Create(); #endregion IDictionary members } @@ -143,7 +143,7 @@ protected virtual SpatialStrategy MakeSpatialStrategy(Config config, IDictionary //A factory for the prefix tree grid // LUCENENET: The second argument was ClassLoader in Java, which should be made into // Assembly in .NET. However, Spatial4n currently doesn't support it. - // In .NET it makes more logical sense to make 2 overloads and throw NullReferenceException + // In .NET it makes more logical sense to make 2 overloads and throw ArgumentNullException // if the second argument is null, anyway. So no need to change this once support has been added. // See: https://github.com/NightOwl888/Spatial4n/issues/1 SpatialPrefixTree grid = SpatialPrefixTreeFactory.MakeSPT(configMap/*, assembly: null*/, ctx); @@ -268,7 +268,7 @@ public static IShape MakeShapeFromString(SpatialStrategy strategy, string name, { return strategy.SpatialContext.ReadShapeFromWkt(shapeStr); } - catch (Exception e) + catch (Exception e) when (e.IsException()) {//InvalidShapeException TODO Console.Error.WriteLine("Shape " + name + " wasn't parseable: " + e + " (skipping it)"); return null; @@ -280,7 +280,7 @@ public static IShape MakeShapeFromString(SpatialStrategy strategy, string name, public override Document MakeDocument(int size) { //TODO consider abusing the 'size' notion to number of shapes per document - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/TrecContentSource.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/TrecContentSource.cs index 7149191051..ec500450df 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Feeds/TrecContentSource.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/TrecContentSource.cs @@ -184,7 +184,7 @@ internal virtual void OpenNextFile() currPathType = TrecDocParser.PathType(f); return; } - catch (Exception e) + catch (Exception e) when (e.IsException()) { if (m_verbose) { @@ -227,7 +227,7 @@ private void DoClose() // LUCENENET specific - separate disposing from closing s { reader?.Dispose(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (m_verbose) { @@ -333,10 +333,10 @@ public override void SetConfig(Config config) string trecDocParserClassName = config.Get("trec.doc.parser", "Lucene.Net.Benchmarks.ByTask.Feeds.TrecGov2Parser, Lucene.Net.Benchmark"); trecDocParser = (TrecDocParser)Activator.CreateInstance(Type.GetType(trecDocParserClassName)); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { // Should not get here. Throw runtime exception. - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } // html parser try @@ -348,7 +348,7 @@ public override void SetConfig(Config config) catch (Exception e) { // Should not get here. Throw runtime exception. - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } // encoding if (m_encoding == null) diff --git a/src/Lucene.Net.Benchmark/ByTask/PerfRunData.cs b/src/Lucene.Net.Benchmark/ByTask/PerfRunData.cs index 2101448a5e..2248443293 100644 --- a/src/Lucene.Net.Benchmark/ByTask/PerfRunData.cs +++ b/src/Lucene.Net.Benchmark/ByTask/PerfRunData.cs @@ -454,9 +454,9 @@ public virtual IQueryMaker GetQueryMaker(ReadTask readTask) qm = (IQueryMaker)Activator.CreateInstance(qmkrClass); qm.SetConfig(config); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } readTaskQueryMaker[readTaskClass] = qm; } diff --git a/src/Lucene.Net.Benchmark/ByTask/Stats/TaskStats.cs b/src/Lucene.Net.Benchmark/ByTask/Stats/TaskStats.cs index a20d344f30..72fc61d9c5 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Stats/TaskStats.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Stats/TaskStats.cs @@ -175,11 +175,11 @@ public virtual void Add(TaskStats stat2) { if (countsByTimeStepMSec != stat2.countsByTimeStepMSec) { - throw new InvalidOperationException("different by-time msec step"); + throw IllegalStateException.Create("different by-time msec step"); } if (countsByTime.Length != stat2.countsByTime.Length) { - throw new InvalidOperationException("different by-time msec count"); + throw IllegalStateException.Create("different by-time msec count"); } for (int i = 0; i < stat2.countsByTime.Length; i++) { diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/AnalyzerFactoryTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/AnalyzerFactoryTask.cs index 50c0236bba..cd3e6ac029 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/AnalyzerFactoryTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/AnalyzerFactoryTask.cs @@ -139,13 +139,13 @@ public override void SetParams(string @params) && !argName.Equals("positionIncrementGap", StringComparison.OrdinalIgnoreCase) && !argName.Equals("offsetGap", StringComparison.OrdinalIgnoreCase)) { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Missing 'name' param to AnalyzerFactory: '" + @params + "'"); } stok.NextToken(); if (stok.TokenType != ':') { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Missing ':' after '" + argName + "' param to AnalyzerFactory"); } @@ -172,9 +172,9 @@ public override void SetParams(string @params) { intArgValue = int.Parse(argValue, CultureInfo.InvariantCulture); } - catch (FormatException e) + catch (Exception e) when (e.IsNumberFormatException()) { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Exception parsing " + argName + " value '" + argValue + "'", e); } if (argName.Equals("positionIncrementGap", StringComparison.OrdinalIgnoreCase)) @@ -204,9 +204,9 @@ public override void SetParams(string @params) { intArgValue = int.Parse(argValue, CultureInfo.InvariantCulture); } - catch (FormatException e) + catch (Exception e) when (e.IsNumberFormatException()) { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Exception parsing " + argName + " value '" + argValue + "'", e); } if (argName.Equals("positionIncrementGap", StringComparison.OrdinalIgnoreCase)) @@ -222,11 +222,11 @@ public override void SetParams(string @params) } case StreamTokenizer.TokenType_EndOfStream: { - throw new Exception("Unexpected EOF: " + stok.ToString()); + throw RuntimeException.Create("Unexpected EOF: " + stok.ToString()); } default: { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Unexpected token: " + stok.ToString()); } } @@ -241,7 +241,7 @@ public override void SetParams(string @params) stok.NextToken(); if (stok.TokenType != ':') { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Missing ':' after '" + argName + "' param to AnalyzerFactory"); } stok.NextToken(); @@ -257,9 +257,9 @@ public override void SetParams(string @params) { intArgValue = int.Parse(stok.StringValue.Trim(), CultureInfo.InvariantCulture); } - catch (FormatException e) + catch (Exception e) when (e.IsNumberFormatException()) { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Exception parsing " + argName + " value '" + stok.StringValue + "'", e); } // Intentional fall-through @@ -288,11 +288,11 @@ public override void SetParams(string @params) } case StreamTokenizer.TokenType_EndOfStream: { - throw new Exception("Unexpected EOF: " + stok.ToString()); + throw RuntimeException.Create("Unexpected EOF: " + stok.ToString()); } default: { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Unexpected token: " + stok.ToString()); } } @@ -304,7 +304,7 @@ public override void SetParams(string @params) clazz = LookupAnalysisClass(argName, typeof(CharFilterFactory)); CreateAnalysisPipelineComponent(stok, clazz); } - catch (ArgumentException /*e*/) + catch (Exception e) when (e.IsIllegalArgumentException()) { try { @@ -313,9 +313,9 @@ public override void SetParams(string @params) CreateAnalysisPipelineComponent(stok, clazz); expectedArgType = ArgType.TOKENFILTER; } - catch (ArgumentException e2) + catch (Exception e2) when (e2.IsIllegalArgumentException()) { - throw new Exception("Line #" + GetLineNumber(stok) + ": Can't find class '" + throw RuntimeException.Create("Line #" + GetLineNumber(stok) + ": Can't find class '" + argName + "' as CharFilterFactory or TokenizerFactory", e2); } } @@ -328,9 +328,9 @@ public override void SetParams(string @params) { clazz = LookupAnalysisClass(className, typeof(TokenFilterFactory)); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Can't find class '" + className + "' as TokenFilterFactory", e); } CreateAnalysisPipelineComponent(stok, clazz); @@ -339,12 +339,12 @@ public override void SetParams(string @params) } default: { - throw new Exception("Line #" + GetLineNumber(stok) + ": Unexpected token: " + stok.ToString()); + throw RuntimeException.Create("Line #" + GetLineNumber(stok) + ": Unexpected token: " + stok.ToString()); } } } } - catch (Exception e) + catch (Exception e) when (e.IsRuntimeException()) { if (e.Message.StartsWith("Line #", StringComparison.Ordinal)) { @@ -352,9 +352,13 @@ public override void SetParams(string @params) } else { - throw new Exception("Line #" + GetLineNumber(stok) + ": ", e); + throw RuntimeException.Create("Line #" + GetLineNumber(stok) + ": ", e); } } + catch (Exception t) when (t.IsThrowable()) + { + throw RuntimeException.Create("Line #" + GetLineNumber(stok) + ": ", t); + } AnalyzerFactory analyzerFactory = new AnalyzerFactory(charFilterFactories, tokenizerFactory, tokenFilterFactories) { @@ -398,7 +402,7 @@ private void CreateAnalysisPipelineComponent(StreamTokenizer stok, Type clazz) { if (parenthetical) { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Unexpected opening parenthesis."); } parenthetical = true; @@ -412,7 +416,7 @@ private void CreateAnalysisPipelineComponent(StreamTokenizer stok, Type clazz) } else { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Unexpected closing parenthesis."); } break; @@ -421,13 +425,13 @@ private void CreateAnalysisPipelineComponent(StreamTokenizer stok, Type clazz) { if (!parenthetical) { - throw new Exception("Line #" + GetLineNumber(stok) + ": Unexpected token '" + stok.StringValue + "'"); + throw RuntimeException.Create("Line #" + GetLineNumber(stok) + ": Unexpected token '" + stok.StringValue + "'"); } string argName = stok.StringValue; stok.NextToken(); if (stok.TokenType != ':') { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Missing ':' after '" + argName + "' param to " + clazz.Name); } stok.NextToken(); @@ -452,11 +456,11 @@ private void CreateAnalysisPipelineComponent(StreamTokenizer stok, Type clazz) } case StreamTokenizer.TokenType_EndOfStream: { - throw new Exception("Unexpected EOF: " + stok.ToString()); + throw RuntimeException.Create("Unexpected EOF: " + stok.ToString()); } default: { - throw new Exception + throw RuntimeException.Create ("Line #" + GetLineNumber(stok) + ": Unexpected token: " + stok.ToString()); } } @@ -464,7 +468,7 @@ private void CreateAnalysisPipelineComponent(StreamTokenizer stok, Type clazz) } } } - WHILE_LOOP_BREAK: { } + WHILE_LOOP_BREAK: { } if (!argMap.ContainsKey("luceneMatchVersion")) { @@ -477,9 +481,9 @@ private void CreateAnalysisPipelineComponent(StreamTokenizer stok, Type clazz) { instance = (AbstractAnalysisFactory)Activator.CreateInstance(clazz, argMap); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception("Line #" + GetLineNumber(stok) + ": ", e); + throw RuntimeException.Create("Line #" + GetLineNumber(stok) + ": ", e); } if (instance is IResourceLoaderAware resourceLoaderAware) { @@ -499,7 +503,7 @@ private void CreateAnalysisPipelineComponent(StreamTokenizer stok, Type clazz) tokenFilterFactories.Add((TokenFilterFactory)instance); } } - catch (Exception e) + catch (Exception e) when (e.IsRuntimeException()) { if (e.Message.StartsWith("Line #", StringComparison.Ordinal)) { @@ -507,9 +511,13 @@ private void CreateAnalysisPipelineComponent(StreamTokenizer stok, Type clazz) } else { - throw new Exception("Line #" + GetLineNumber(stok) + ": ", e); + throw RuntimeException.Create("Line #" + GetLineNumber(stok) + ": ", e); } } + catch (Exception t) when (t.IsThrowable()) + { + throw RuntimeException.Create("Line #" + GetLineNumber(stok) + ": ", t); + } } /// @@ -543,7 +551,7 @@ public virtual Type LookupAnalysisClass(string className, Type expectedType) if (result == null) { - throw new TypeLoadException("Can't find class '" + className + throw ClassNotFoundException.Create("Can't find class '" + className + "' or '" + LUCENE_ANALYSIS_PACKAGE_PREFIX + className + "'"); } } @@ -564,7 +572,7 @@ public virtual Type LookupAnalysisClass(string className, Type expectedType) return TokenFilterFactory.LookupClass(analysisComponentName); } - throw new TypeLoadException("Can't find class '" + className + "'"); + throw ClassNotFoundException.Create("Can't find class '" + className + "'"); } /// diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/CommitTaxonomyIndexTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/CommitTaxonomyIndexTask.cs index 4b8cc2cc5d..3273eb7279 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/CommitTaxonomyIndexTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/CommitTaxonomyIndexTask.cs @@ -39,7 +39,7 @@ public override int DoLogic() } else { - throw new InvalidOperationException("TaxonomyWriter is not currently open"); + throw IllegalStateException.Create("TaxonomyWriter is not currently open"); } return 1; diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/CreateIndexTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/CreateIndexTask.cs index af63cfa483..d517578307 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/CreateIndexTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/CreateIndexTask.cs @@ -70,7 +70,7 @@ public static IndexDeletionPolicy GetIndexDeletionPolicy(Config config) Type deletionPolicyType = Type.GetType(deletionPolicyName); if (deletionPolicyType == null) { - throw new Exception("Unrecognized deletion policy type '" + deletionPolicyName + "'"); + throw RuntimeException.Create("Unrecognized deletion policy type '" + deletionPolicyName + "'"); // LUCENENET: In .NET we don't get an error here, so throwing one for compatibility } else if (deletionPolicyType.Equals(typeof(NoDeletionPolicy))) { @@ -82,9 +82,9 @@ public static IndexDeletionPolicy GetIndexDeletionPolicy(Config config) { return (IndexDeletionPolicy)Activator.CreateInstance(deletionPolicyType); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception("unable to instantiate class '" + deletionPolicyName + "' as IndexDeletionPolicy", e); + throw RuntimeException.Create("unable to instantiate class '" + deletionPolicyName + "' as IndexDeletionPolicy", e); } } } @@ -115,7 +115,7 @@ public static IndexWriterConfig CreateWriterConfig(Config config, PerfRunData ru Type mergeSchedulerType = Type.GetType(mergeScheduler); if (mergeSchedulerType == null) { - throw new Exception("Unrecognized merge scheduler type '" + mergeScheduler + "'"); + throw RuntimeException.Create("Unrecognized merge scheduler type '" + mergeScheduler + "'"); // LUCENENET: We don't get an exception in this case, so throwing one for compatibility } else if (mergeSchedulerType.Equals(typeof(NoMergeScheduler))) { @@ -127,9 +127,9 @@ public static IndexWriterConfig CreateWriterConfig(Config config, PerfRunData ru { iwConf.MergeScheduler = (IMergeScheduler)Activator.CreateInstance(mergeSchedulerType); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception("unable to instantiate class '" + mergeScheduler + "' as merge scheduler", e); + throw RuntimeException.Create("unable to instantiate class '" + mergeScheduler + "' as merge scheduler", e); } if (mergeScheduler.Equals("Lucene.Net.Index.ConcurrentMergeScheduler", StringComparison.Ordinal)) @@ -149,9 +149,9 @@ public static IndexWriterConfig CreateWriterConfig(Config config, PerfRunData ru Type clazz = Type.GetType(defaultCodec); iwConf.Codec = (Codec)Activator.CreateInstance(clazz); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception("Couldn't instantiate Codec: " + defaultCodec, e); + throw RuntimeException.Create("Couldn't instantiate Codec: " + defaultCodec, e); } } @@ -161,7 +161,7 @@ public static IndexWriterConfig CreateWriterConfig(Config config, PerfRunData ru Type mergePolicyType = Type.GetType(mergePolicy); if (mergePolicyType == null) { - throw new Exception("Unrecognized merge policy type '" + mergePolicy + "'"); + throw RuntimeException.Create("Unrecognized merge policy type '" + mergePolicy + "'"); // LUCENENET: We don't get an exception in this case, so throwing one for compatibility } else if (mergePolicyType.Equals(typeof(NoMergePolicy))) { @@ -173,9 +173,9 @@ public static IndexWriterConfig CreateWriterConfig(Config config, PerfRunData ru { iwConf.MergePolicy = (MergePolicy)Activator.CreateInstance(mergePolicyType); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception("unable to instantiate class '" + mergePolicy + "' as merge policy", e); + throw RuntimeException.Create("unable to instantiate class '" + mergePolicy + "' as merge policy", e); } iwConf.MergePolicy.NoCFSRatio = isCompound ? 1.0 : 0.0; if (iwConf.MergePolicy is LogMergePolicy logMergePolicy) diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/ForceMergeTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/ForceMergeTask.cs index 61c49d173a..68f6b90bad 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/ForceMergeTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/ForceMergeTask.cs @@ -39,7 +39,7 @@ public override int DoLogic() { if (maxNumSegments == -1) { - throw new InvalidOperationException("required argument (maxNumSegments) was not specified"); + throw IllegalStateException.Create("required argument (maxNumSegments) was not specified"); } IndexWriter iw = RunData.IndexWriter; iw.ForceMerge(maxNumSegments); diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/NearRealtimeReaderTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/NearRealtimeReaderTask.cs index e06a1687b5..f51aa6def9 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/NearRealtimeReaderTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/NearRealtimeReaderTask.cs @@ -54,12 +54,12 @@ public override int DoLogic() IndexWriter w = runData.IndexWriter; if (w == null) { - throw new Exception("please open the writer before invoking NearRealtimeReader"); + throw RuntimeException.Create("please open the writer before invoking NearRealtimeReader"); } if (runData.GetIndexReader() != null) { - throw new Exception("please close the existing reader before invoking NearRealtimeReader"); + throw RuntimeException.Create("please close the existing reader before invoking NearRealtimeReader"); } diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/NewAnalyzerTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/NewAnalyzerTask.cs index d2a5dc8751..979bc88ce0 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/NewAnalyzerTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/NewAnalyzerTask.cs @@ -50,7 +50,7 @@ public static Analyzer CreateAnalyzer(string className) LuceneVersion.LUCENE_CURRENT); #pragma warning restore 612, 618 } - catch (MissingMethodException /*nsme*/) + catch (Exception nsme) when (nsme.IsNoSuchMethodException()) { // otherwise use default ctor return (Analyzer)Activator.CreateInstance(clazz); @@ -96,7 +96,7 @@ public override int DoLogic() analyzer = CreateAnalyzer(coreClassName); analyzerName = coreClassName; } - catch (TypeLoadException /*e*/) + catch (Exception e) when (e.IsClassNotFoundException()) { // If not a core analyzer, try the base analysis package analyzerName = "Lucene.Net.Analysis." + analyzerName; @@ -106,9 +106,9 @@ public override int DoLogic() } RunData.Analyzer = analyzer; } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception("Error creating Analyzer: " + analyzerName, e); + throw RuntimeException.Create("Error creating Analyzer: " + analyzerName, e); } return 1; } @@ -160,13 +160,12 @@ public override void SetParams(string @params) } default: { - //throw new RuntimeException("Unexpected token: " + stok.ToString()); - throw new Exception("Unexpected token: " + stok.ToString()); + throw RuntimeException.Create("Unexpected token: " + stok.ToString()); } } } } - catch (Exception e) + catch (Exception e) when (e.IsRuntimeException()) { if (e.Message.StartsWith("Line #", StringComparison.Ordinal)) { @@ -174,9 +173,13 @@ public override void SetParams(string @params) } else { - throw new Exception("Line #" + (stok.LineNumber + AlgLineNum) + ": ", e); + throw RuntimeException.Create("Line #" + (stok.LineNumber + AlgLineNum) + ": ", e); } } + catch (Exception t) when (t.IsThrowable()) + { + throw RuntimeException.Create("Line #" + (stok.LineNumber + AlgLineNum) + ": ", t); + } } /// diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/NewCollationAnalyzerTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/NewCollationAnalyzerTask.cs index 8f7865cd06..513943aa17 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/NewCollationAnalyzerTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/NewCollationAnalyzerTask.cs @@ -102,16 +102,16 @@ public override int DoLogic() try { CultureInfo locale = RunData.Locale; - if (locale == null) throw new Exception( + if (locale == null) throw RuntimeException.Create( "Locale must be set with the NewLocale task!"); Analyzer analyzer = CreateAnalyzer(locale, impl); RunData.Analyzer = analyzer; Console.WriteLine("Changed Analyzer to: " + analyzer.GetType().Name + "(" + locale + ")"); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception("Error creating Analyzer: impl=" + impl, e); + throw RuntimeException.Create("Error creating Analyzer: impl=" + impl, e); } return 1; } @@ -136,11 +136,11 @@ public override void SetParams(string @params) //else if (value.Equals("jdk", StringComparison.OrdinalIgnoreCase)) // impl = Implementation.JDK; else - throw new Exception("Unknown parameter " + param); + throw RuntimeException.Create("Unknown parameter " + param); } else { - throw new Exception("Unknown parameter " + param); + throw RuntimeException.Create("Unknown parameter " + param); } } } diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/PerfTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/PerfTask.cs index 144899475e..a85b132570 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/PerfTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/PerfTask.cs @@ -328,7 +328,7 @@ public virtual void SetParams(string @params) { if (!SupportsParams) { - throw new NotSupportedException(GetName() + " does not support command line parameters."); + throw UnsupportedOperationException.Create(GetName() + " does not support command line parameters."); } this.m_params = @params; } diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/SearchWithSortTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/SearchWithSortTask.cs index 1b8acf1f38..4f7c1746ca 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/SearchWithSortTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/SearchWithSortTask.cs @@ -86,7 +86,7 @@ public override void SetParams(string sortField) } else { - throw new Exception("You must specify the sort type ie page:int,subject:string"); + throw RuntimeException.Create("You must specify the sort type ie page:int,subject:string"); } sortField0 = new SortField(fieldName, (SortFieldType)Enum.Parse(typeof(SortFieldType), typeString, true)); } @@ -127,7 +127,7 @@ public override Sort Sort { if (sort == null) { - throw new InvalidOperationException("No sort field was set"); + throw IllegalStateException.Create("No sort field was set"); } return sort; } diff --git a/src/Lucene.Net.Benchmark/ByTask/Tasks/TaskSequence.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/TaskSequence.cs index cfa6ef063d..7710d22a55 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/TaskSequence.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/TaskSequence.cs @@ -169,9 +169,9 @@ public override void Run() { count = task.RunAndMaybeStats(letChildReport); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } @@ -383,9 +383,9 @@ public override void Run() { outerInstance.exhausted = true; } - 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.Benchmark/ByTask/Tasks/UpdateDocTask.cs b/src/Lucene.Net.Benchmark/ByTask/Tasks/UpdateDocTask.cs index 68cab7f7ea..6bf50ec69d 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Tasks/UpdateDocTask.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Tasks/UpdateDocTask.cs @@ -68,7 +68,7 @@ public override int DoLogic() string docID = doc.Get(DocMaker.ID_FIELD); if (docID == null) { - throw new InvalidOperationException("document must define the docid field"); + throw IllegalStateException.Create("document must define the docid field"); } IndexWriter iw = RunData.IndexWriter; iw.UpdateDocument(new Term(DocMaker.ID_FIELD, docID), doc); diff --git a/src/Lucene.Net.Benchmark/ByTask/Utils/Algorithm.cs b/src/Lucene.Net.Benchmark/ByTask/Utils/Algorithm.cs index fcf86ef348..c9654006be 100644 --- a/src/Lucene.Net.Benchmark/ByTask/Utils/Algorithm.cs +++ b/src/Lucene.Net.Benchmark/ByTask/Utils/Algorithm.cs @@ -126,7 +126,7 @@ public Algorithm(PerfRunData runData) } case StreamTokenizer.TokenType_EndOfStream: { - throw new Exception("Unexpexted EOF: - " + stok.ToString()); + throw RuntimeException.Create("Unexpexted EOF: - " + stok.ToString()); } case '"': case '\'': @@ -395,7 +395,7 @@ private Type TaskClass(/*Config config, // LUCENENET: Not referenced */ string t } } // can only get here if failed to instantiate - throw new TypeLoadException(taskName + " not found in packages " + Collections.ToString(taskPackages)); + throw ClassNotFoundException.Create(taskName + " not found in packages " + Arrays.ToString(taskPackages)); } private static Type LoadType(string assemblyName, string typeName) // LUCENENET: CA1822: Mark members as static diff --git a/src/Lucene.Net.Benchmark/Quality/QualityQuery.cs b/src/Lucene.Net.Benchmark/Quality/QualityQuery.cs index f849b49c05..cc45910d14 100644 --- a/src/Lucene.Net.Benchmark/Quality/QualityQuery.cs +++ b/src/Lucene.Net.Benchmark/Quality/QualityQuery.cs @@ -93,7 +93,7 @@ public virtual int CompareTo(QualityQuery other) int nOther = int.Parse(other.queryID, CultureInfo.InvariantCulture); return n - nOther; } - catch (FormatException /*e*/) + catch (Exception e) when (e.IsNumberFormatException()) { // fall back to string comparison return queryID.CompareToOrdinal(other.queryID); diff --git a/src/Lucene.Net.Benchmark/Quality/QualityStats.cs b/src/Lucene.Net.Benchmark/Quality/QualityStats.cs index 11c248838c..f24db9fb9b 100644 --- a/src/Lucene.Net.Benchmark/Quality/QualityStats.cs +++ b/src/Lucene.Net.Benchmark/Quality/QualityStats.cs @@ -88,7 +88,7 @@ public virtual void AddResult(int n, bool isRelevant, long docNameExtractTime) { if (Math.Abs(numPoints + 1 - n) > 1E-6) { - throw new ArgumentException("point " + n + " illegal after " + numPoints + " points!"); + throw new ArgumentOutOfRangeException(nameof(n), "point " + n + " illegal after " + numPoints + " points!");// LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (isRelevant) { diff --git a/src/Lucene.Net.Benchmark/Support/Sax/SAXParseException.cs b/src/Lucene.Net.Benchmark/Support/Sax/SAXParseException.cs index d06147cfd0..8190884103 100644 --- a/src/Lucene.Net.Benchmark/Support/Sax/SAXParseException.cs +++ b/src/Lucene.Net.Benchmark/Support/Sax/SAXParseException.cs @@ -153,16 +153,16 @@ public SAXParseException(string message, string publicId, string systemId, Init(publicId, systemId, lineNumber, columnNumber); } -#if FEATURE_SERIALIZABLE_EXCEPTIONS /// /// Construct a new exception with no message. /// - // LUCENENET specific for serialization - public SAXParseException(string message) + // LUCENENET: For testing purposes + internal SAXParseException(string message) : base(message) { } +#if FEATURE_SERIALIZABLE_EXCEPTIONS /// /// Initializes a new instance of this class with serialized data. /// diff --git a/src/Lucene.Net.Benchmark/Support/TagSoup/Parser.cs b/src/Lucene.Net.Benchmark/Support/TagSoup/Parser.cs index 3308e130ca..87c239c405 100644 --- a/src/Lucene.Net.Benchmark/Support/TagSoup/Parser.cs +++ b/src/Lucene.Net.Benchmark/Support/TagSoup/Parser.cs @@ -15,6 +15,7 @@ // The TagSoup parser using J2N.Text; +using Lucene; using Lucene.Net.Support; using Sax; using Sax.Ext; @@ -520,7 +521,7 @@ private TextReader GetReader(InputSource s) //TODO: Safe? r = new StreamReader(i, encoding); // } - //catch (UnsupportedEncodingException e) { + //catch (Exception e) when (e.IsUnsupportedEncodingException()) { // r = new StreamReader(i); // } } @@ -922,7 +923,7 @@ private void Push(Element e) { theEntityResolver.ResolveEntity(theDoctypePublicId, theDoctypeSystemId); } - catch (IOException) + catch (Exception ioe) when (ioe.IsIOException()) { } // Can't be thrown for root I believe. } diff --git a/src/Lucene.Net.Benchmark/Support/TagSoup/XMLWriter.cs b/src/Lucene.Net.Benchmark/Support/TagSoup/XMLWriter.cs index d5b4f8f678..6561c42005 100644 --- a/src/Lucene.Net.Benchmark/Support/TagSoup/XMLWriter.cs +++ b/src/Lucene.Net.Benchmark/Support/TagSoup/XMLWriter.cs @@ -13,7 +13,7 @@ // OF ANY KIND, either express or implied; not even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - +using Lucene; using Sax; using Sax.Ext; using Sax.Helpers; @@ -581,7 +581,7 @@ public override void EndDocument() { Flush(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { throw new SAXException(e.Message, e); } @@ -1229,7 +1229,7 @@ private void Write(char c) { output.Write(c); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { throw new SAXException(e.ToString(), e); } @@ -1249,7 +1249,7 @@ private void Write(string s) { output.Write(s); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { throw new SAXException(e.ToString(), e); } diff --git a/src/Lucene.Net.Benchmark/Utils/ExtractReuters.cs b/src/Lucene.Net.Benchmark/Utils/ExtractReuters.cs index c8f62ad646..b34c36cbaa 100644 --- a/src/Lucene.Net.Benchmark/Utils/ExtractReuters.cs +++ b/src/Lucene.Net.Benchmark/Utils/ExtractReuters.cs @@ -126,9 +126,9 @@ protected virtual void ExtractFile(FileInfo sgmFile) } } } - 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.Benchmark/Utils/ExtractWikipedia.cs b/src/Lucene.Net.Benchmark/Utils/ExtractWikipedia.cs index 01f082c813..71e7e48189 100644 --- a/src/Lucene.Net.Benchmark/Utils/ExtractWikipedia.cs +++ b/src/Lucene.Net.Benchmark/Utils/ExtractWikipedia.cs @@ -91,9 +91,9 @@ public virtual void Create(string id, string title, string time, string body) using TextWriter writer = new StreamWriter(new FileStream(f.FullName, FileMode.Create, FileAccess.Write), Encoding.UTF8); writer.Write(contents.ToString()); } - 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.Classification/Utils/DatasetSplitter.cs b/src/Lucene.Net.Classification/Utils/DatasetSplitter.cs index c1a09e243c..ca5acb07f1 100644 --- a/src/Lucene.Net.Classification/Utils/DatasetSplitter.cs +++ b/src/Lucene.Net.Classification/Utils/DatasetSplitter.cs @@ -142,7 +142,7 @@ public virtual void Split(AtomicReader originalIndex, Directory trainingIndex, D b++; } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { throw new IOException("Exceptio in DatasetSplitter", e); } diff --git a/src/Lucene.Net.Codecs/Appending/AppendingPostingsFormat.cs b/src/Lucene.Net.Codecs/Appending/AppendingPostingsFormat.cs index 3890477240..a82d9ac129 100644 --- a/src/Lucene.Net.Codecs/Appending/AppendingPostingsFormat.cs +++ b/src/Lucene.Net.Codecs/Appending/AppendingPostingsFormat.cs @@ -36,7 +36,7 @@ public AppendingPostingsFormat() public override FieldsConsumer FieldsConsumer(SegmentWriteState state) { - throw new NotSupportedException("This codec can only be used for reading"); + throw UnsupportedOperationException.Create("This codec can only be used for reading"); } public override FieldsProducer FieldsProducer(SegmentReadState state) diff --git a/src/Lucene.Net.Codecs/BlockTerms/BlockTermsReader.cs b/src/Lucene.Net.Codecs/BlockTerms/BlockTermsReader.cs index f54f385157..3684236a9e 100644 --- a/src/Lucene.Net.Codecs/BlockTerms/BlockTermsReader.cs +++ b/src/Lucene.Net.Codecs/BlockTerms/BlockTermsReader.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Support; @@ -378,7 +378,7 @@ public override SeekStatus SeekCeil(BytesRef target) { if (indexEnum == null) { - throw new InvalidOperationException("terms index was not loaded"); + throw IllegalStateException.Create("terms index was not loaded"); } //System.out.println("BTR.seek seg=" + segment + " target=" + fieldInfo.name + ":" + target.utf8ToString() + " " + target + " current=" + term().utf8ToString() + " " + term() + " indexIsCurrent=" + indexIsCurrent + " didIndexNext=" + didIndexNext + " seekPending=" + seekPending + " divisor=" + indexReader.getDivisor() + " this=" + this); @@ -827,7 +827,7 @@ public override void SeekExact(long ord) //System.out.println("BTR.seek by ord ord=" + ord); if (indexEnum == null) { - throw new InvalidOperationException("terms index was not loaded"); + throw IllegalStateException.Create("terms index was not loaded"); } if (Debugging.AssertsEnabled) Debugging.Assert(ord < outerInstance.numTerms); @@ -867,7 +867,7 @@ public override long Ord { if (!doOrd) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } return state.Ord; } diff --git a/src/Lucene.Net.Codecs/BlockTerms/VariableGapTermsIndexReader.cs b/src/Lucene.Net.Codecs/BlockTerms/VariableGapTermsIndexReader.cs index 90d721a8e4..32ee9c2d3c 100644 --- a/src/Lucene.Net.Codecs/BlockTerms/VariableGapTermsIndexReader.cs +++ b/src/Lucene.Net.Codecs/BlockTerms/VariableGapTermsIndexReader.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Support; @@ -152,7 +152,7 @@ public override long Seek(BytesRef target) } else { - throw new NullReferenceException("_current.Output is null"); // LUCENENET NOTE: NullReferenceException would be thrown in Java, so doing it here + throw new NullReferenceException("current.Output is null"); // LUCENENET NOTE: NullReferenceException would be thrown in Java, so doing it here } } @@ -174,16 +174,16 @@ public override long Next() } else { - throw new NullReferenceException("_current.Output is null"); // LUCENENET NOTE: NullReferenceException would be thrown in Java, so doing it here + throw new NullReferenceException("current.Output is null"); // LUCENENET NOTE: NullReferenceException would be thrown in Java, so doing it here } } } - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); public override long Seek(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } diff --git a/src/Lucene.Net.Codecs/Bloom/BloomFilteringPostingsFormat.cs b/src/Lucene.Net.Codecs/Bloom/BloomFilteringPostingsFormat.cs index 621850fde8..003f72e3c2 100644 --- a/src/Lucene.Net.Codecs/Bloom/BloomFilteringPostingsFormat.cs +++ b/src/Lucene.Net.Codecs/Bloom/BloomFilteringPostingsFormat.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; @@ -114,7 +114,7 @@ public override FieldsConsumer FieldsConsumer(SegmentWriteState state) { if (_delegatePostingsFormat == null) { - throw new InvalidOperationException("Error - constructed without a choice of PostingsFormat"); + throw UnsupportedOperationException.Create("Error - constructed without a choice of PostingsFormat"); } return new BloomFilteredFieldsConsumer(this, _delegatePostingsFormat.FieldsConsumer(state), state); } diff --git a/src/Lucene.Net.Codecs/Bloom/FuzzySet.cs b/src/Lucene.Net.Codecs/Bloom/FuzzySet.cs index a1bcb9c3d5..47a5ed5318 100644 --- a/src/Lucene.Net.Codecs/Bloom/FuzzySet.cs +++ b/src/Lucene.Net.Codecs/Bloom/FuzzySet.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Store; using Lucene.Net.Util; using System; @@ -52,13 +52,13 @@ public class FuzzySet public static HashFunction HashFunctionForVersion(int version) { if (version < VERSION_START) - throw new ArgumentException("Version " + version + " is too old, expected at least " + - VERSION_START); - + throw new ArgumentOutOfRangeException(nameof(version), "Version " + version + " is too old, expected at least " + + VERSION_START);// LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) + if (version > VERSION_CURRENT) - throw new ArgumentException("Version " + version + " is too new, expected at most " + - VERSION_CURRENT); - + throw new ArgumentOutOfRangeException(nameof(version), "Version " + version + " is too new, expected at most " + + VERSION_CURRENT);// LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) + return MurmurHash2.INSTANCE; } diff --git a/src/Lucene.Net.Codecs/DiskDV/DiskDocValuesProducer.cs b/src/Lucene.Net.Codecs/DiskDV/DiskDocValuesProducer.cs index 8412a76834..89855b64c1 100644 --- a/src/Lucene.Net.Codecs/DiskDV/DiskDocValuesProducer.cs +++ b/src/Lucene.Net.Codecs/DiskDV/DiskDocValuesProducer.cs @@ -1,4 +1,5 @@ -using Lucene.Net.Codecs.Lucene45; +using Lucene.Net.Codecs.Lucene45; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Util.Packed; @@ -42,7 +43,7 @@ protected override MonotonicBlockPackedReader GetAddressInstance(IndexInput data protected override MonotonicBlockPackedReader GetIntervalInstance(IndexInput data, FieldInfo field, BinaryEntry bytes) { - throw new InvalidOperationException(); // LUCENENET NOTE: This was AssertionError in Lucene + throw AssertionError.Create(); } protected override MonotonicBlockPackedReader GetOrdIndexInstance(IndexInput data, FieldInfo field, diff --git a/src/Lucene.Net.Codecs/Memory/DirectDocValuesConsumer.cs b/src/Lucene.Net.Codecs/Memory/DirectDocValuesConsumer.cs index ee63af2679..5f8ecf990c 100644 --- a/src/Lucene.Net.Codecs/Memory/DirectDocValuesConsumer.cs +++ b/src/Lucene.Net.Codecs/Memory/DirectDocValuesConsumer.cs @@ -373,7 +373,7 @@ public bool MoveNext() public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } #region IDisposable Support diff --git a/src/Lucene.Net.Codecs/Memory/DirectDocValuesProducer.cs b/src/Lucene.Net.Codecs/Memory/DirectDocValuesProducer.cs index 41eaef90fe..9d40f0d8fb 100644 --- a/src/Lucene.Net.Codecs/Memory/DirectDocValuesProducer.cs +++ b/src/Lucene.Net.Codecs/Memory/DirectDocValuesProducer.cs @@ -271,7 +271,7 @@ private NumericDocValues LoadNumeric(NumericEntry entry) } default: - throw new InvalidOperationException(); + throw AssertionError.Create(); } } @@ -574,7 +574,7 @@ public override IBits GetDocsWithField(FieldInfo field) NumericEntry ne = numerics[field.Number]; return GetMissingBits(field.Number, ne.missingOffset, ne.missingBytes); default: - throw new ArgumentOutOfRangeException(); + throw AssertionError.Create(); } } diff --git a/src/Lucene.Net.Codecs/Memory/DirectPostingsFormat.cs b/src/Lucene.Net.Codecs/Memory/DirectPostingsFormat.cs index 34020744e5..8153b782ed 100644 --- a/src/Lucene.Net.Codecs/Memory/DirectPostingsFormat.cs +++ b/src/Lucene.Net.Codecs/Memory/DirectPostingsFormat.cs @@ -379,7 +379,7 @@ public DirectField(SegmentReadState state, string field, Terms termsIn, int minS int numTerms = (int) termsIn.Count; if (numTerms == -1) { - throw new ArgumentException("codec does not provide Terms.size()"); + throw new ArgumentException("codec does not provide Terms.Count"); } terms = new TermAndSkip[numTerms]; termOffsets = new int[1 + numTerms]; @@ -1751,12 +1751,12 @@ public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPos public override SeekStatus SeekCeil(BytesRef term) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } @@ -1789,6 +1789,7 @@ public DocsEnum Reset(int[] postings) public override int NextDoc() { + // LUCENENET: Refactored to avoid throwing IndexOutOfRangeExcpetion in the normal flow upto++; if (liveDocs == null) { @@ -2244,13 +2245,9 @@ public override int NextDoc() upto++; if (liveDocs == null) { - try - { + // LUCENENET: Proactively check bounds so we don't have to catch and ingore an exception + if (upto >= 0 && upto < docIDs.Length) return docID = docIDs[upto]; - } - catch (IndexOutOfRangeException) - { - } } else { diff --git a/src/Lucene.Net.Codecs/Memory/FSTOrdTermsReader.cs b/src/Lucene.Net.Codecs/Memory/FSTOrdTermsReader.cs index e36151467d..48007dfeef 100644 --- a/src/Lucene.Net.Codecs/Memory/FSTOrdTermsReader.cs +++ b/src/Lucene.Net.Codecs/Memory/FSTOrdTermsReader.cs @@ -441,10 +441,10 @@ public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPos // and should have related tests public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); } // Iterates through all terms in this field @@ -654,7 +654,7 @@ internal override void DecodeStats() public override SeekStatus SeekCeil(BytesRef target) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override bool MoveNext() diff --git a/src/Lucene.Net.Codecs/Memory/FSTOrdTermsWriter.cs b/src/Lucene.Net.Codecs/Memory/FSTOrdTermsWriter.cs index bf86ba3732..671604b188 100644 --- a/src/Lucene.Net.Codecs/Memory/FSTOrdTermsWriter.cs +++ b/src/Lucene.Net.Codecs/Memory/FSTOrdTermsWriter.cs @@ -195,7 +195,7 @@ protected override void Dispose(bool disposing) { if (blockOut == null) return; - IOException ioe = null; + Exception ioe = null; // LUCENENET: No need to cast to IOExcpetion try { var blockDirStart = blockOut.GetFilePointer(); @@ -227,7 +227,7 @@ protected override void Dispose(bool disposing) CodecUtil.WriteFooter(indexOut); CodecUtil.WriteFooter(blockOut); } - catch (IOException ioe2) + catch (Exception ioe2) when (ioe2.IsIOException()) { ioe = ioe2; } diff --git a/src/Lucene.Net.Codecs/Memory/FSTTermsReader.cs b/src/Lucene.Net.Codecs/Memory/FSTTermsReader.cs index cf2154b81d..3a3a9fcde4 100644 --- a/src/Lucene.Net.Codecs/Memory/FSTTermsReader.cs +++ b/src/Lucene.Net.Codecs/Memory/FSTTermsReader.cs @@ -298,10 +298,10 @@ public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPos public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); } diff --git a/src/Lucene.Net.Codecs/Memory/FSTTermsWriter.cs b/src/Lucene.Net.Codecs/Memory/FSTTermsWriter.cs index f9a08b54c1..dce0660599 100644 --- a/src/Lucene.Net.Codecs/Memory/FSTTermsWriter.cs +++ b/src/Lucene.Net.Codecs/Memory/FSTTermsWriter.cs @@ -1,4 +1,5 @@ using Lucene.Net.Util.Fst; +using System; using System.Collections.Generic; using System.IO; @@ -173,7 +174,7 @@ protected override void Dispose(bool disposing) { if (_output == null) return; - IOException ioe = null; + Exception ioe = null; // LUCENENET: No need to cast to IOExcpetion try { // write field summary @@ -196,7 +197,7 @@ protected override void Dispose(bool disposing) WriteTrailer(_output, dirStart); CodecUtil.WriteFooter(_output); } - catch (IOException ioe2) + catch (Exception ioe2) when (ioe2.IsIOException()) { ioe = ioe2; } diff --git a/src/Lucene.Net.Codecs/Memory/MemoryDocValuesConsumer.cs b/src/Lucene.Net.Codecs/Memory/MemoryDocValuesConsumer.cs index bd67a5bdf6..f831bc8273 100644 --- a/src/Lucene.Net.Codecs/Memory/MemoryDocValuesConsumer.cs +++ b/src/Lucene.Net.Codecs/Memory/MemoryDocValuesConsumer.cs @@ -468,9 +468,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); } _current.Bytes = buffer; @@ -502,9 +502,11 @@ public void Dispose() this.ords.Dispose(); } - public void Reset() + // LUCENENET: Remove() not supported in .NET + + public void Reset() // LUCENENET: Required by .NET contract, but not supported here. { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } diff --git a/src/Lucene.Net.Codecs/Memory/MemoryDocValuesProducer.cs b/src/Lucene.Net.Codecs/Memory/MemoryDocValuesProducer.cs index 82aaaf561b..49428e6045 100644 --- a/src/Lucene.Net.Codecs/Memory/MemoryDocValuesProducer.cs +++ b/src/Lucene.Net.Codecs/Memory/MemoryDocValuesProducer.cs @@ -273,7 +273,7 @@ private NumericDocValues LoadNumeric(FieldInfo field) ramBytesUsed.AddAndGet(quotientReader.RamBytesUsed()); return new NumericDocValuesAnonymousClass3(min, mult, quotientReader); default: - throw new InvalidOperationException(); + throw AssertionError.Create(); } } @@ -475,9 +475,9 @@ public override void LookupOrd(int ord, BytesRef result) result.Length = 0; Util.ToBytesRef(output, result); } - catch (IOException bogus) + catch (Exception bogus) when (bogus.IsIOException()) { - throw new Exception(bogus.ToString(), bogus); + throw RuntimeException.Create(bogus); } } @@ -499,9 +499,9 @@ public override int LookupTerm(BytesRef key) return (int) -o.Output - 1; } } - catch (IOException bogus) + catch (Exception bogus) when (bogus.IsIOException()) { - throw new Exception(bogus.ToString(), bogus); + throw RuntimeException.Create(bogus); } } @@ -609,9 +609,9 @@ public override void LookupOrd(long ord, BytesRef result) result.Length = 0; Util.ToBytesRef(output, result); } - catch (IOException bogus) + catch (Exception bogus) when (bogus.IsIOException()) { - throw new Exception(bogus.ToString(), bogus); + throw RuntimeException.Create(bogus); } } @@ -633,9 +633,9 @@ public override long LookupTerm(BytesRef key) return -o.Output.Value - 1; } } - catch (IOException bogus) + catch (Exception bogus) when (bogus.IsIOException()) { - throw new Exception(bogus.ToString(), bogus); + throw RuntimeException.Create(bogus); } } @@ -691,7 +691,7 @@ public override IBits GetDocsWithField(FieldInfo field) var ne = numerics[field.Number]; return GetMissingBits(field.Number, ne.missingOffset, ne.missingBytes); default: - throw new InvalidOperationException(); + throw AssertionError.Create(); } } @@ -806,18 +806,18 @@ public override void SeekExact(long ord) public override long Ord => input.Current.Output.Value; - public override int DocFreq => throw new NotSupportedException(); + public override int DocFreq => throw UnsupportedOperationException.Create(); - public override long TotalTermFreq => throw new NotSupportedException(); + public override long TotalTermFreq => throw UnsupportedOperationException.Create(); public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } diff --git a/src/Lucene.Net.Codecs/Memory/MemoryPostingsFormat.cs b/src/Lucene.Net.Codecs/Memory/MemoryPostingsFormat.cs index 9d51b0ee12..7a9ff0188e 100644 --- a/src/Lucene.Net.Codecs/Memory/MemoryPostingsFormat.cs +++ b/src/Lucene.Net.Codecs/Memory/MemoryPostingsFormat.cs @@ -879,12 +879,12 @@ public override long TotalTermFreq public override void SeekExact(long ord) { // NOTE: we could add this... - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } - public override long Ord => throw + public override long Ord => // NOTE: we could add this... - new NotSupportedException(); + throw UnsupportedOperationException.Create(); } private sealed class TermsReader : Terms diff --git a/src/Lucene.Net.Codecs/Sep/SepPostingsWriter.cs b/src/Lucene.Net.Codecs/Sep/SepPostingsWriter.cs index 59e18bda1c..b1d552d54e 100644 --- a/src/Lucene.Net.Codecs/Sep/SepPostingsWriter.cs +++ b/src/Lucene.Net.Codecs/Sep/SepPostingsWriter.cs @@ -202,7 +202,7 @@ public override int SetField(FieldInfo fieldInfo) // LUCENENET specific - to avoid boxing, changed from CompareTo() to IndexOptionsComparer.Compare() if (IndexOptionsComparer.Default.Compare(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"); } skipListWriter.SetIndexOptions(indexOptions); storePayloads = indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS && fieldInfo.HasPayloads; diff --git a/src/Lucene.Net.Codecs/SimpleText/SimpleTextDocValuesReader.cs b/src/Lucene.Net.Codecs/SimpleText/SimpleTextDocValuesReader.cs index 9e1515deeb..64818071e6 100644 --- a/src/Lucene.Net.Codecs/SimpleText/SimpleTextDocValuesReader.cs +++ b/src/Lucene.Net.Codecs/SimpleText/SimpleTextDocValuesReader.cs @@ -4,9 +4,7 @@ using Lucene.Net.Util; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Globalization; -using System.IO; using System.Text; namespace Lucene.Net.Codecs.SimpleText @@ -133,7 +131,7 @@ internal SimpleTextDocValuesReader(SegmentReadState state, string ext) } else { - throw new ArgumentOutOfRangeException(); + throw AssertionError.Create(); } } @@ -194,9 +192,9 @@ public override long Get(int docId) SimpleTextUtil.ReadLine(_input, _scratch); // read the line telling us if its real or not return (long)((decimal)_field.MinValue + bd); // LUCENENET specific - use decimal rather than BigInteger } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } } } @@ -235,9 +233,9 @@ public bool Get(int index) SimpleTextUtil.ReadLine(_input, _scratch); // 'T' or 'F' return _scratch.Bytes[_scratch.Offset] == (byte)'T'; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } @@ -289,9 +287,9 @@ public override void Get(int docId, BytesRef result) len = int.Parse(Encoding.UTF8.GetString(_scratch.Bytes, _scratch.Offset + SimpleTextDocValuesWriter.LENGTH.Length, _scratch.Length - SimpleTextDocValuesWriter.LENGTH.Length), NumberStyles.Integer, CultureInfo.InvariantCulture); } - catch (FormatException ex) + catch (Exception pe) when (pe.IsParseException()) { - throw new CorruptIndexException("failed to parse int value (resource=" + _input + ")", ex); + throw new CorruptIndexException("failed to parse int value (resource=" + _input + ")", pe); } result.Bytes = new byte[len]; @@ -299,9 +297,9 @@ public override void Get(int docId, BytesRef result) result.Length = len; _input.ReadBytes(result.Bytes, 0, len); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } } } @@ -345,9 +343,9 @@ public bool Get(int index) len = int.Parse(Encoding.UTF8.GetString(_scratch.Bytes, _scratch.Offset + SimpleTextDocValuesWriter.LENGTH.Length, _scratch.Length - SimpleTextDocValuesWriter.LENGTH.Length), NumberStyles.Number, CultureInfo.InvariantCulture); } - catch (FormatException ex) + catch (Exception pe) when (pe.IsParseException()) { - throw new CorruptIndexException("failed to parse int value (resource=" + _input + ")", ex); + throw new CorruptIndexException("failed to parse int value (resource=" + _input + ")", pe); } // skip past bytes @@ -357,9 +355,9 @@ public bool Get(int index) SimpleTextUtil.ReadLine(_input, _scratch); // 'T' or 'F' return _scratch.Bytes[_scratch.Offset] == (byte)'T'; } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } } @@ -413,15 +411,15 @@ public override int GetOrd(int docId) // LUCNENENET: .NET doesn't have a way to specify a pattern with integer, but all of the standard ones are built in. return int.Parse(_scratch.Utf8ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture) - 1; } - catch (Exception pe) + catch (Exception pe) when (pe.IsParseException()) { var e = new CorruptIndexException($"failed to parse ord (resource={_input})", pe); throw e; } } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } } @@ -443,9 +441,8 @@ public override void LookupOrd(int ord, BytesRef result) // LUCNENENET: .NET doesn't have a way to specify a pattern with integer, but all of the standard ones are built in. len = int.Parse(Encoding.UTF8.GetString(_scratch.Bytes, _scratch.Offset + SimpleTextDocValuesWriter.LENGTH.Length, _scratch.Length - SimpleTextDocValuesWriter.LENGTH.Length), NumberStyles.Integer, CultureInfo.InvariantCulture); - } - catch (Exception pe) + catch (Exception pe) when (pe.IsParseException()) { var e = new CorruptIndexException($"failed to parse int length (resource={_input})", pe); throw e; @@ -456,9 +453,9 @@ public override void LookupOrd(int ord, BytesRef result) result.Length = len; _input.ReadBytes(result.Bytes, 0, len); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } } @@ -521,9 +518,9 @@ public override void SetDocument(int docID) _currentOrds = ordList.Length == 0 ? Arrays.Empty() : ordList.Split(',').TrimEnd(); _currentIndex = 0; } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } } @@ -547,7 +544,7 @@ public override void LookupOrd(long ord, BytesRef result) len = int.Parse(Encoding.UTF8.GetString(_scratch.Bytes, _scratch.Offset + SimpleTextDocValuesWriter.LENGTH.Length, _scratch.Length - SimpleTextDocValuesWriter.LENGTH.Length), NumberStyles.Integer, CultureInfo.InvariantCulture); } - catch (Exception pe) + catch (Exception pe) when (pe.IsParseException()) { var e = new CorruptIndexException("failed to parse int length (resource=" + _input + ")", pe); throw e; @@ -558,9 +555,9 @@ public override void LookupOrd(long ord, BytesRef result) result.Length = len; _input.ReadBytes(result.Bytes, 0, len); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } } @@ -580,7 +577,7 @@ public override IBits GetDocsWithField(FieldInfo field) case DocValuesType.NUMERIC: return GetNumericDocsWithField(field); default: - throw new ArgumentOutOfRangeException(); + throw AssertionError.Create(); } } diff --git a/src/Lucene.Net.Codecs/SimpleText/SimpleTextFieldsReader.cs b/src/Lucene.Net.Codecs/SimpleText/SimpleTextFieldsReader.cs index 949461120f..7439c7094d 100644 --- a/src/Lucene.Net.Codecs/SimpleText/SimpleTextFieldsReader.cs +++ b/src/Lucene.Net.Codecs/SimpleText/SimpleTextFieldsReader.cs @@ -180,11 +180,11 @@ public override BytesRef Next() public override BytesRef Term => _fstEnum.Current.Input; - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override int DocFreq => _docFreq; diff --git a/src/Lucene.Net.Codecs/SimpleText/SimpleTextSegmentInfoWriter.cs b/src/Lucene.Net.Codecs/SimpleText/SimpleTextSegmentInfoWriter.cs index d83b6722ef..684d4a0d60 100644 --- a/src/Lucene.Net.Codecs/SimpleText/SimpleTextSegmentInfoWriter.cs +++ b/src/Lucene.Net.Codecs/SimpleText/SimpleTextSegmentInfoWriter.cs @@ -119,7 +119,7 @@ public override void Write(Directory dir, SegmentInfo si, FieldInfos fis, IOCont { dir.DeleteFile(segFileName); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { //Esnure we throw original exeception } diff --git a/src/Lucene.Net.Codecs/SimpleText/SimpleTextStoredFieldsReader.cs b/src/Lucene.Net.Codecs/SimpleText/SimpleTextStoredFieldsReader.cs index e9c38f5b51..41338f45bd 100644 --- a/src/Lucene.Net.Codecs/SimpleText/SimpleTextStoredFieldsReader.cs +++ b/src/Lucene.Net.Codecs/SimpleText/SimpleTextStoredFieldsReader.cs @@ -78,7 +78,7 @@ public SimpleTextStoredFieldsReader(Directory directory, SegmentInfo si, FieldIn { Dispose(); } - catch + catch (Exception t) when (t.IsThrowable()) { // ensure we throw our original exception } @@ -163,7 +163,7 @@ public override void VisitDocument(int n, StoredFieldVisitor visitor) } else { - throw new Exception("unknown field type"); + throw RuntimeException.Create("unknown field type"); } switch (visitor.NeedsField(fieldInfo)) @@ -227,7 +227,7 @@ public override object Clone() { if (_input == null) { - throw new ObjectDisposedException(this.GetType().FullName, "this FieldsReader is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this FieldsReader is disposed."); } return new SimpleTextStoredFieldsReader(_offsets, (IndexInput) _input.Clone(), _fieldInfos); } diff --git a/src/Lucene.Net.Codecs/SimpleText/SimpleTextStoredFieldsWriter.cs b/src/Lucene.Net.Codecs/SimpleText/SimpleTextStoredFieldsWriter.cs index af24d2afba..de6be9fe47 100644 --- a/src/Lucene.Net.Codecs/SimpleText/SimpleTextStoredFieldsWriter.cs +++ b/src/Lucene.Net.Codecs/SimpleText/SimpleTextStoredFieldsWriter.cs @@ -192,7 +192,7 @@ public override void Abort() { Dispose(); } - catch // ignored + catch (Exception ignored) when (ignored.IsThrowable()) { } IOUtils.DeleteFilesIgnoringExceptions(_directory, @@ -203,7 +203,7 @@ public override void Finish(FieldInfos fis, int numDocs) { if (_numDocsWritten != numDocs) { - throw new Exception("mergeFields produced an invalid result: docCount is " + numDocs + " but only saw " + + throw RuntimeException.Create("mergeFields produced an invalid result: docCount is " + numDocs + " but only saw " + _numDocsWritten + " file=" + _output + "; now aborting this merge to prevent index corruption"); } diff --git a/src/Lucene.Net.Codecs/SimpleText/SimpleTextTermVectorsReader.cs b/src/Lucene.Net.Codecs/SimpleText/SimpleTextTermVectorsReader.cs index 25b58ca9d8..7efda283fb 100644 --- a/src/Lucene.Net.Codecs/SimpleText/SimpleTextTermVectorsReader.cs +++ b/src/Lucene.Net.Codecs/SimpleText/SimpleTextTermVectorsReader.cs @@ -77,7 +77,7 @@ public SimpleTextTermVectorsReader(Directory directory, SegmentInfo si, IOContex { Dispose(); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // ensure we throw our original exception } @@ -235,7 +235,7 @@ public override object Clone() { if (_input == null) { - throw new ObjectDisposedException(this.GetType().FullName, "this TermVectorsReader is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this TermVectorsReader is disposed."); } return new SimpleTextTermVectorsReader(_offsets, (IndexInput)_input.Clone()); } @@ -383,7 +383,7 @@ public override SeekStatus SeekCeil(BytesRef text) public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override bool MoveNext() @@ -409,7 +409,7 @@ public override BytesRef Next() public override BytesRef Term => _current.Key; - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); public override int DocFreq => 1; @@ -557,7 +557,7 @@ public override int NextPosition() // IndexOutOfRangeException if we didn't, which doesn't really provide good feedback as to what the cause is. // This matches the behavior of Lucene 8.x. See #267. if (((_positions != null && _nextPos < _positions.Length) || _startOffsets != null && _nextPos < _startOffsets.Length) == false) - throw new InvalidOperationException("Read past last position"); + throw IllegalStateException.Create("Read past last position"); if (_positions != null) { diff --git a/src/Lucene.Net.Codecs/SimpleText/SimpleTextTermVectorsWriter.cs b/src/Lucene.Net.Codecs/SimpleText/SimpleTextTermVectorsWriter.cs index aa7cd6d32c..8011853173 100644 --- a/src/Lucene.Net.Codecs/SimpleText/SimpleTextTermVectorsWriter.cs +++ b/src/Lucene.Net.Codecs/SimpleText/SimpleTextTermVectorsWriter.cs @@ -183,7 +183,7 @@ public override sealed void Abort() { Dispose(); } - catch // ignored + catch (Exception t) when (t.IsThrowable()) { } IOUtils.DeleteFilesIgnoringExceptions(_directory, @@ -194,7 +194,7 @@ public override void Finish(FieldInfos fis, int numDocs) { if (_numDocsWritten != numDocs) { - throw new Exception("mergeVectors produced an invalid result: mergedDocs is " + numDocs + + throw RuntimeException.Create("mergeVectors produced an invalid result: mergedDocs is " + numDocs + " but vec numDocs is " + _numDocsWritten + " file=" + _output + "; now aborting this merge to prevent index corruption"); } diff --git a/src/Lucene.Net.Demo/IndexFiles.cs b/src/Lucene.Net.Demo/IndexFiles.cs index af988e971b..efae0eb4bd 100644 --- a/src/Lucene.Net.Demo/IndexFiles.cs +++ b/src/Lucene.Net.Demo/IndexFiles.cs @@ -122,7 +122,7 @@ public static void Main(string[] args) DateTime end = DateTime.UtcNow; Console.WriteLine((end - start).TotalMilliseconds + " total milliseconds"); } - catch (IOException e) + catch (Exception e) { Console.WriteLine(" caught a " + e.GetType() + "\n with message: " + e.Message); diff --git a/src/Lucene.Net.Expressions/ExpressionComparator.cs b/src/Lucene.Net.Expressions/ExpressionComparator.cs index 15db756646..184d4aa040 100644 --- a/src/Lucene.Net.Expressions/ExpressionComparator.cs +++ b/src/Lucene.Net.Expressions/ExpressionComparator.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Queries.Function; using Lucene.Net.Search; @@ -57,9 +57,9 @@ public override void SetScorer(Scorer scorer) context["scorer"] = scorer; scores = source.GetValues(context, readerContext); } - 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.Expressions/ExpressionFunctionValues.cs b/src/Lucene.Net.Expressions/ExpressionFunctionValues.cs index 3f8dbdfb01..798699fb32 100644 --- a/src/Lucene.Net.Expressions/ExpressionFunctionValues.cs +++ b/src/Lucene.Net.Expressions/ExpressionFunctionValues.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Queries.Function; +using Lucene.Net.Queries.Function; using Lucene.Net.Queries.Function.DocValues; using System; @@ -35,8 +35,8 @@ internal class ExpressionFunctionValues : DoubleDocValues internal ExpressionFunctionValues(ValueSource parent, Expression expression, FunctionValues[] functionValues) : base(parent) { - this.expression = expression ?? throw new ArgumentNullException(nameof(expression)); - this.functionValues = functionValues ?? throw new ArgumentNullException(nameof(functionValues)); + this.expression = expression ?? throw new ArgumentNullException(nameof(expression)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) + this.functionValues = functionValues ?? throw new ArgumentNullException(nameof(functionValues)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } public override double DoubleVal(int document) diff --git a/src/Lucene.Net.Expressions/ExpressionRescorer.cs b/src/Lucene.Net.Expressions/ExpressionRescorer.cs index 8f0d7c91b3..5a948e2268 100644 --- a/src/Lucene.Net.Expressions/ExpressionRescorer.cs +++ b/src/Lucene.Net.Expressions/ExpressionRescorer.cs @@ -61,7 +61,7 @@ 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; @@ -70,7 +70,7 @@ public override int Advance(int target) public override int NextDoc() { - throw new NotSupportedException("FakeScorer doesn't support NextDoc()"); + throw UnsupportedOperationException.Create("FakeScorer doesn't support NextDoc()"); } public override float GetScore() @@ -83,11 +83,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(); } } diff --git a/src/Lucene.Net.Expressions/ExpressionValueSource.cs b/src/Lucene.Net.Expressions/ExpressionValueSource.cs index e99e231028..f96e911c40 100644 --- a/src/Lucene.Net.Expressions/ExpressionValueSource.cs +++ b/src/Lucene.Net.Expressions/ExpressionValueSource.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Index; +using Lucene.Net.Index; using Lucene.Net.Queries.Function; using Lucene.Net.Search; using Lucene.Net.Support; @@ -37,12 +37,12 @@ internal sealed class ExpressionValueSource : ValueSource internal ExpressionValueSource(Bindings bindings, Expression expression) { - if (bindings == null) + if (bindings is null) { - throw new ArgumentNullException(nameof(bindings)); + throw new ArgumentNullException(nameof(bindings)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } - this.expression = expression ?? throw new ArgumentNullException(nameof(expression)); + this.expression = expression ?? throw new ArgumentNullException(nameof(expression)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) variables = new ValueSource[expression.Variables.Length]; bool needsScores = false; for (int i = 0; i < variables.Length; i++) @@ -65,7 +65,8 @@ internal ExpressionValueSource(Bindings bindings, Expression expression) { if (source == null) { - throw new InvalidOperationException("Internal error. Variable (" + expression.Variables[i] + // LUCENENET specific: Changed from RuntimeException to InvalidOperationException to match .NET conventions + throw IllegalStateException.Create("Internal error. Variable (" + expression.Variables[i] + ") does not exist."); } } @@ -95,8 +96,9 @@ public override FunctionValues GetValues(IDictionary context, AtomicReaderContex values = variables[i].GetValues(context, readerContext); if (values == null) { + // LUCENENET specific: Changed from RuntimeException to InvalidOperationException to match .NET conventions #pragma warning disable IDE0016 // Use 'throw' expression - throw new InvalidOperationException($"Internal error. External ({externalName}) does not exist."); + throw IllegalStateException.Create($"Internal error. External ({externalName}) does not exist."); #pragma warning restore IDE0016 // Use 'throw' expression } valuesCache[externalName] = values; diff --git a/src/Lucene.Net.Expressions/JS/JavascriptCompiler.cs b/src/Lucene.Net.Expressions/JS/JavascriptCompiler.cs index 0a122de3ac..d2f444350c 100644 --- a/src/Lucene.Net.Expressions/JS/JavascriptCompiler.cs +++ b/src/Lucene.Net.Expressions/JS/JavascriptCompiler.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using J2N.Text; using Antlr.Runtime; using Antlr.Runtime.Tree; @@ -164,7 +164,7 @@ private JavascriptCompiler(string sourceText) /// The set of functions to compile with private JavascriptCompiler(string sourceText, IDictionary functions) { - this.sourceText = sourceText ?? throw new ArgumentNullException(nameof(sourceText)); + this.sourceText = sourceText ?? throw new ArgumentNullException(nameof(sourceText)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) this.functions = functions; } @@ -185,16 +185,10 @@ private Expression CompileExpression() Activator.CreateInstance(dynamicType.CreateTypeInfo().AsType(), sourceText, externalsMap.Keys.ToArray()); } - - catch (MemberAccessException exception) - { - throw new InvalidOperationException("An internal error occurred attempting to compile the expression (" - + sourceText + ").", exception); - } - catch (TargetInvocationException exception) + catch (Exception exception) when (exception.IsInstantiationException() || exception.IsIllegalAccessException() || + exception.IsNoSuchMethodException() || exception.IsInvocationTargetException()) { - throw new InvalidOperationException("An internal error occurred attempting to compile the expression (" - + sourceText + ").", exception); + throw IllegalStateException.Create("An internal error occurred attempting to compile the expression (" + sourceText + ").", exception); } } @@ -495,7 +489,7 @@ private void RecursiveCompile(ITree current, Type expected) default: { - throw new InvalidOperationException("Unknown operation specified: (" + current.Text + ")."); + throw IllegalStateException.Create("Unknown operation specified: (" + current.Text + ")."); } } @@ -586,6 +580,9 @@ private ITree GetAntlrComputedExpressionTree() { throw new ArgumentException(re.Message, re); } + // LUCENENET: Antlr 3.5.1 doesn't ever wrap ParseException, so the other catch block + // for RuntimeException that wraps ParseException would have + // been completely unnecesary in Java and is also unnecessary here. } /// The default set of functions available to expressions. @@ -606,7 +603,7 @@ private static IDictionary LoadDefaultFunctions() // LUCENEN string[] vals = property.Value.Split(',').TrimEnd(); if (vals.Length != 3) { - throw new Exception("Error reading Javascript functions from settings"); + throw Error.Create("Error reading Javascript functions from settings"); } string typeName = vals[0]; @@ -630,9 +627,9 @@ private static IDictionary LoadDefaultFunctions() // LUCENEN map[property.Key] = method; } } - catch (Exception e) + catch (Exception e) when (e.IsNoSuchMethodException() || e.IsClassNotFoundException() || e.IsIOException()) { - throw new Exception("Cannot resolve function", e); + throw Error.Create("Cannot resolve function", e); } return map.AsReadOnly(); } diff --git a/src/Lucene.Net.Expressions/JS/JavascriptLexer.cs b/src/Lucene.Net.Expressions/JS/JavascriptLexer.cs index 0e9a70f3a5..8a635a9afb 100644 --- a/src/Lucene.Net.Expressions/JS/JavascriptLexer.cs +++ b/src/Lucene.Net.Expressions/JS/JavascriptLexer.cs @@ -1,4 +1,4 @@ -/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -26,6 +26,7 @@ using System.Runtime.Serialization; #endif using Antlr.Runtime; +using J2N.Text; using Lucene.Net.Support; namespace Lucene.Net.Expressions.JS @@ -117,9 +118,7 @@ internal class JavascriptLexer : Lexer public override void DisplayRecognitionError(string[] tokenNames, RecognitionException re) { string message = " unexpected character '" + (char)re.Character + "' at position (" + re.CharPositionInLine + ")."; - ParseException parseException = new ParseException(message, re.CharPositionInLine); - - throw new InvalidOperationException(parseException.Message, parseException); + throw new ParseException(message, re.CharPositionInLine, re); } // delegates @@ -2178,35 +2177,4 @@ public override string Description #pragma warning restore IDE0052 // Remove unread private members } } - - // LUCENENET: It is no longer good practice to use binary serialization. - // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 -#if FEATURE_SERIALIZABLE_EXCEPTIONS - [Serializable] -#endif - public class ParseException : Exception - { - public ParseException(string message, int charPositionInLine) - : base(message + ": " + charPositionInLine) - { - } - -#if FEATURE_SERIALIZABLE_EXCEPTIONS - // For testing - public ParseException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of this class with serialized data. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - protected ParseException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } -#endif - } } diff --git a/src/Lucene.Net.Expressions/JS/JavascriptParser.cs b/src/Lucene.Net.Expressions/JS/JavascriptParser.cs index 8da6329b99..b0936d1eb9 100644 --- a/src/Lucene.Net.Expressions/JS/JavascriptParser.cs +++ b/src/Lucene.Net.Expressions/JS/JavascriptParser.cs @@ -1,4 +1,4 @@ -/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -23,6 +23,7 @@ using Antlr.Runtime; using Antlr.Runtime.Tree; +using J2N.Text; using Lucene.Net.Support; using System; using System.Diagnostics.CodeAnalysis; @@ -205,9 +206,7 @@ public override void DisplayRecognitionError(string[] tokenNames, RecognitionExc } } } - //ParseException parseException = new ParseException(message, re.CharPositionInLine); - - throw new InvalidOperationException(message); + throw new ParseException(message, re.CharPositionInLine, re); } public static string GetReadableTokenString(IToken token) diff --git a/src/Lucene.Net.Expressions/ScoreFunctionValues.cs b/src/Lucene.Net.Expressions/ScoreFunctionValues.cs index a28bc3f2bd..c6eb9c1058 100644 --- a/src/Lucene.Net.Expressions/ScoreFunctionValues.cs +++ b/src/Lucene.Net.Expressions/ScoreFunctionValues.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Queries.Function; using Lucene.Net.Queries.Function.DocValues; using Lucene.Net.Search; @@ -46,9 +46,9 @@ public override double DoubleVal(int document) if (Debugging.AssertsEnabled) Debugging.Assert(document == scorer.DocID); 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.Expressions/ScoreValueSource.cs b/src/Lucene.Net.Expressions/ScoreValueSource.cs index a4fdca32de..6a67e1433c 100644 --- a/src/Lucene.Net.Expressions/ScoreValueSource.cs +++ b/src/Lucene.Net.Expressions/ScoreValueSource.cs @@ -43,7 +43,7 @@ public override FunctionValues GetValues(IDictionary context, AtomicReaderContex Scorer v = (Scorer)context["scorer"]; if (v == null) { - throw new InvalidOperationException("Expressions referencing the score can only be used for sorting"); + throw IllegalStateException.Create("Expressions referencing the score can only be used for sorting"); } return new ScoreFunctionValues(this, v); } diff --git a/src/Lucene.Net.Expressions/SimpleBindings.cs b/src/Lucene.Net.Expressions/SimpleBindings.cs index 14e676e474..dacfb12826 100644 --- a/src/Lucene.Net.Expressions/SimpleBindings.cs +++ b/src/Lucene.Net.Expressions/SimpleBindings.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Queries.Function; +using Lucene.Net.Queries.Function; using Lucene.Net.Queries.Function.ValueSources; using Lucene.Net.Search; using System; @@ -115,7 +115,7 @@ public override ValueSource GetValueSource(string name) default: { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } @@ -128,7 +128,18 @@ public void Validate() { if (o is Expression expr) { - expr.GetValueSource(this); +#if FEATURE_STACKOVERFLOWEXCEPTION__ISCATCHABLE + try + { +#endif + expr.GetValueSource(this); +#if FEATURE_STACKOVERFLOWEXCEPTION__ISCATCHABLE + } + catch (Exception e) when (e.IsStackOverflowError()) + { + throw new ArgumentException("Recursion Error: Cycle detected originating in (" + expr.SourceText + ")"); + } +#endif } } } diff --git a/src/Lucene.Net.Facet/DrillDownQuery.cs b/src/Lucene.Net.Facet/DrillDownQuery.cs index 9754c7fb2e..0c3c2619ab 100644 --- a/src/Lucene.Net.Facet/DrillDownQuery.cs +++ b/src/Lucene.Net.Facet/DrillDownQuery.cs @@ -162,7 +162,7 @@ private void Merge(string dim, string[] path) { // App called .add(dim, customQuery) and then tried to // merge a facet label in: - throw new Exception("cannot merge with custom Query"); + throw RuntimeException.Create("cannot merge with custom Query"); } string indexedField = config.GetDimConfig(dim).IndexFieldName; diff --git a/src/Lucene.Net.Facet/DrillSidewaysQuery.cs b/src/Lucene.Net.Facet/DrillSidewaysQuery.cs index 123c90f67c..2f57ed5dd3 100644 --- a/src/Lucene.Net.Facet/DrillSidewaysQuery.cs +++ b/src/Lucene.Net.Facet/DrillSidewaysQuery.cs @@ -146,7 +146,7 @@ public override void Normalize(float norm, float topLevelBoost) public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { // We can only run as a top scorer: - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override BulkScorer GetBulkScorer(AtomicReaderContext context, bool scoreDocsInOrder, IBits acceptDocs) diff --git a/src/Lucene.Net.Facet/DrillSidewaysScorer.cs b/src/Lucene.Net.Facet/DrillSidewaysScorer.cs index 53694bb58f..9f8e167e1a 100644 --- a/src/Lucene.Net.Facet/DrillSidewaysScorer.cs +++ b/src/Lucene.Net.Facet/DrillSidewaysScorer.cs @@ -68,7 +68,7 @@ public override bool Score(ICollector collector, int maxDoc) { if (maxDoc != int.MaxValue) { - throw new ArgumentException("maxDoc must be System.Int32.MaxValue"); + throw new ArgumentOutOfRangeException(nameof(maxDoc), "maxDoc must be System.Int32.MaxValue"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } //if (DEBUG) { // System.out.println("\nscore: reader=" + context.reader()); @@ -748,7 +748,7 @@ public FakeScorer(DrillSidewaysScorer outerInstance) 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 => outerInstance.collectDocID; @@ -757,7 +757,7 @@ public override int Advance(int target) public override int NextDoc() { - throw new NotSupportedException("FakeScorer doesn't support nextDoc()"); + throw UnsupportedOperationException.Create("FakeScorer doesn't support NextDoc()"); } public override float GetScore() @@ -775,7 +775,7 @@ public override ICollection GetChildren() return new[] { new Scorer.ChildScorer(outerInstance.baseScorer, "MUST") }; } - public override Weight Weight => throw new NotSupportedException(); + public override Weight Weight => throw UnsupportedOperationException.Create(); } internal class DocsAndCost : IComparable diff --git a/src/Lucene.Net.Facet/FacetsCollector.cs b/src/Lucene.Net.Facet/FacetsCollector.cs index 2c2d723761..15929fa1b7 100644 --- a/src/Lucene.Net.Facet/FacetsCollector.cs +++ b/src/Lucene.Net.Facet/FacetsCollector.cs @@ -237,9 +237,9 @@ public static TopDocs Search(IndexSearcher searcher, Query q, Filter filter, int /// public static TopFieldDocs Search(IndexSearcher searcher, 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 (TopFieldDocs)DoSearch(searcher, null, q, filter, n, sort, false, false, fc); } @@ -250,9 +250,9 @@ public static TopFieldDocs Search(IndexSearcher searcher, Query q, Filter filter /// 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(() => new LimitTokenPositionFilter(new MockTokenizer(new StringReader("one two three four five")), 0)); } } } \ No newline at end of file diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenPositionFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenPositionFilterFactory.cs index 02adb41e82..8b1e2910e1 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenPositionFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestLimitTokenPositionFilterFactory.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 TestMissingParam() TokenFilterFactory("LimitTokenPosition"); fail(); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { assertTrue("exception doesn't mention param: " + e.Message, 0 < e.Message.IndexOf(LimitTokenPositionFilterFactory.MAX_TOKEN_POSITION_KEY, StringComparison.Ordinal)); } @@ -91,7 +91,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("LimitTokenPosition", "maxTokenPosition", "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/TestRemoveDuplicatesTokenFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestRemoveDuplicatesTokenFilterFactory.cs index e63a26b5a7..f4f353cebf 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestRemoveDuplicatesTokenFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestRemoveDuplicatesTokenFilterFactory.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 NUnit.Framework; @@ -59,7 +59,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("RemoveDuplicates", "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/TestScandinavianFoldingFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestScandinavianFoldingFilterFactory.cs index f1878eff8d..0a09aee6d1 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestScandinavianFoldingFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestScandinavianFoldingFilterFactory.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; @@ -45,7 +45,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("ScandinavianFolding", "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/TestScandinavianNormalizationFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestScandinavianNormalizationFilterFactory.cs index ed32817c68..4e06ad80f1 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestScandinavianNormalizationFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestScandinavianNormalizationFilterFactory.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; @@ -45,7 +45,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("ScandinavianNormalization", "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/TestStemmerOverrideFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestStemmerOverrideFilterFactory.cs index aed217d1d4..089ca1ccfe 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestStemmerOverrideFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestStemmerOverrideFilterFactory.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; @@ -61,7 +61,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("StemmerOverride", "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/TestTrimFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestTrimFilterFactory.cs index a0ae00d483..7fdf5079e6 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestTrimFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestTrimFilterFactory.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using NUnit.Framework; using System; using System.IO; @@ -47,7 +47,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("Trim", "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/TestTruncateTokenFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestTruncateTokenFilterFactory.cs index 85972451f2..1716c22e37 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestTruncateTokenFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestTruncateTokenFilterFactory.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using NUnit.Framework; using System; using System.IO; @@ -51,7 +51,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("Truncate", TruncateTokenFilterFactory.PREFIX_LENGTH_KEY, "5", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameter(s):")); } @@ -68,7 +68,7 @@ public virtual void TestNonPositivePrefixLengthArgument() TokenFilterFactory("Truncate", TruncateTokenFilterFactory.PREFIX_LENGTH_KEY, "-5"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains(TruncateTokenFilterFactory.PREFIX_LENGTH_KEY + " parameter must be a positive number: -5")); } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/EdgeNGramTokenFilterTest.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/EdgeNGramTokenFilterTest.cs index bf9f7d66f8..f5a89d0de1 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/EdgeNGramTokenFilterTest.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/EdgeNGramTokenFilterTest.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.Core; using Lucene.Net.Analysis.Miscellaneous; @@ -51,7 +51,7 @@ public virtual void TestInvalidInput() new EdgeNGramTokenFilter(TEST_VERSION_CURRENT, input, EdgeNGramTokenFilter.Side.FRONT, 0, 0); #pragma warning restore 612, 618 } - catch (ArgumentException) + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { gotException = true; } @@ -68,7 +68,7 @@ public virtual void TestInvalidInput2() new EdgeNGramTokenFilter(TEST_VERSION_CURRENT, input, EdgeNGramTokenFilter.Side.FRONT, 2, 1); #pragma warning restore 612, 618 } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { gotException = true; } @@ -85,7 +85,7 @@ public virtual void TestInvalidInput3() new EdgeNGramTokenFilter(TEST_VERSION_CURRENT, input, EdgeNGramTokenFilter.Side.FRONT, -1, 2); #pragma warning restore 612, 618 } - catch (ArgumentException) + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { gotException = true; } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/EdgeNGramTokenizerTest.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/EdgeNGramTokenizerTest.cs index 5117288366..f39aa8d5df 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/EdgeNGramTokenizerTest.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/EdgeNGramTokenizerTest.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 NUnit.Framework; @@ -46,7 +46,7 @@ public virtual void TestInvalidInput() { new EdgeNGramTokenizer(TEST_VERSION_CURRENT, input, 0, 0); } - catch (ArgumentException) + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { gotException = true; } @@ -61,7 +61,7 @@ public virtual void TestInvalidInput2() { new EdgeNGramTokenizer(TEST_VERSION_CURRENT, input, 2, 1); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { gotException = true; } @@ -76,7 +76,7 @@ public virtual void TestInvalidInput3() { new EdgeNGramTokenizer(TEST_VERSION_CURRENT, input, -1, 2); } - catch (ArgumentException) + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { gotException = true; } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/NGramTokenFilterTest.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/NGramTokenFilterTest.cs index 5f3d67ab71..103dbdddaa 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/NGramTokenFilterTest.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/NGramTokenFilterTest.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.Core; using Lucene.Net.Analysis.Miscellaneous; @@ -48,7 +48,7 @@ public virtual void TestInvalidInput() { new NGramTokenFilter(TEST_VERSION_CURRENT, input, 2, 1); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { gotException = true; } @@ -63,7 +63,7 @@ public virtual void TestInvalidInput2() { new NGramTokenFilter(TEST_VERSION_CURRENT, input, 0, 1); } - catch (ArgumentException) + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { gotException = true; } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/NGramTokenizerTest.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/NGramTokenizerTest.cs index cbc8b0f354..04b4da9e3f 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/NGramTokenizerTest.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/NGramTokenizerTest.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using J2N; using J2N.Text; using Lucene.Net.Analysis.TokenAttributes; @@ -48,7 +48,7 @@ public virtual void TestInvalidInput() { new NGramTokenizer(TEST_VERSION_CURRENT, input, 2, 1); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { gotException = true; } @@ -63,7 +63,7 @@ public virtual void TestInvalidInput2() { new NGramTokenizer(TEST_VERSION_CURRENT, input, 0, 1); } - catch (ArgumentException) + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { gotException = true; } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/TestNGramFilters.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/TestNGramFilters.cs index 7d5fe94ea6..ffe293ea2c 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/TestNGramFilters.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/NGram/TestNGramFilters.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; @@ -159,7 +159,7 @@ public virtual void TestBogusArguments() TokenizerFactory("NGram", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -169,7 +169,7 @@ public virtual void TestBogusArguments() TokenizerFactory("EdgeNGram", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -179,7 +179,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("NGram", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -189,7 +189,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("EdgeNGram", "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/No/TestNorwegianLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/No/TestNorwegianLightStemFilterFactory.cs index c86c8858f7..de14ff8634 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/No/TestNorwegianLightStemFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/No/TestNorwegianLightStemFilterFactory.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("NorwegianLightStem", "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/No/TestNorwegianMinimalStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/No/TestNorwegianMinimalStemFilterFactory.cs index 5371d0f129..8d0b71482e 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/No/TestNorwegianMinimalStemFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/No/TestNorwegianMinimalStemFilterFactory.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("NorwegianMinimalStem", "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/Pattern/TestPatternReplaceCharFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceCharFilterFactory.cs index a6683f5b92..18db2db270 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceCharFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceCharFilterFactory.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; @@ -75,7 +75,7 @@ public virtual void TestBogusArguments() CharFilterFactory("PatternReplace", "pattern", "something", "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/Pattern/TestPatternReplaceFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceFilterFactory.cs index 716b2d59af..efbaf8f58b 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceFilterFactory.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 TestBogusArguments() TokenFilterFactory("PatternReplace", "pattern", "something", "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/Pattern/TestPatternTokenizerFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternTokenizerFactory.cs index 458f6125a2..f06b2152f0 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternTokenizerFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternTokenizerFactory.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() TokenizerFactory("Pattern", "pattern", "something", "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/Payloads/TestDelimitedPayloadTokenFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Payloads/TestDelimitedPayloadTokenFilterFactory.cs index d9e65dc438..003012ae4f 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Payloads/TestDelimitedPayloadTokenFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Payloads/TestDelimitedPayloadTokenFilterFactory.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 NUnit.Framework; @@ -78,7 +78,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("DelimitedPayload", "encoder", "float", "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/Pt/TestPortugueseLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pt/TestPortugueseLightStemFilterFactory.cs index 77d2ecb0fc..5dc7608ea9 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pt/TestPortugueseLightStemFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pt/TestPortugueseLightStemFilterFactory.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("PortugueseLightStem", "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/Pt/TestPortugueseMinimalStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pt/TestPortugueseMinimalStemFilterFactory.cs index fcc31f1a75..2cf84da06c 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pt/TestPortugueseMinimalStemFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pt/TestPortugueseMinimalStemFilterFactory.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("PortugueseMinimalStem", "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/Pt/TestPortugueseStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pt/TestPortugueseStemFilterFactory.cs index c13b380ff8..a4b0318c44 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pt/TestPortugueseStemFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pt/TestPortugueseStemFilterFactory.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("PortugueseStem", "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/Reverse/TestReverseStringFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Reverse/TestReverseStringFilterFactory.cs index 7f68c82cfe..52a2de9b6e 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Reverse/TestReverseStringFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Reverse/TestReverseStringFilterFactory.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("ReverseString", "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/Ru/TestRussianFilters.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ru/TestRussianFilters.cs index 94c630b4ed..e6444e6bcf 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ru/TestRussianFilters.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ru/TestRussianFilters.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 TestBogusArguments() TokenizerFactory("RussianLetter", "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/Ru/TestRussianLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ru/TestRussianLightStemFilterFactory.cs index 7295602a8d..8e378006aa 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ru/TestRussianLightStemFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Ru/TestRussianLightStemFilterFactory.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("RussianLightStem", "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/Shingle/TestShingleFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Shingle/TestShingleFilterFactory.cs index a5495e22d9..72fabaabe5 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Shingle/TestShingleFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Shingle/TestShingleFilterFactory.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; @@ -203,7 +203,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("Shingle", "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/Sinks/TokenRangeSinkTokenizerTest.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Sinks/TokenRangeSinkTokenizerTest.cs index 50a3556563..7d3f9c6e2e 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Sinks/TokenRangeSinkTokenizerTest.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Sinks/TokenRangeSinkTokenizerTest.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using NUnit.Framework; using System; using System.IO; @@ -54,7 +54,7 @@ public virtual void Test() [Test] public virtual void TestIllegalArguments() { - Assert.Throws(() => { + Assert.Throws(() => { new TokenRangeSinkFilter(4, 2); }); } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Snowball/TestSnowballPorterFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Snowball/TestSnowballPorterFilterFactory.cs index a1544ab820..471ff8aa4f 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Snowball/TestSnowballPorterFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Snowball/TestSnowballPorterFilterFactory.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.Tartarus.Snowball.Ext; @@ -73,7 +73,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("SnowballPorter", "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/Standard/TestStandardFactories.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Standard/TestStandardFactories.cs index e30f10f9d7..c582ec0504 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Standard/TestStandardFactories.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Standard/TestStandardFactories.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using System.Text; using Lucene.Net.Analysis.Util; using NUnit.Framework; @@ -160,7 +160,7 @@ public virtual void TestBogusArguments() TokenizerFactory("Standard", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -170,7 +170,7 @@ public virtual void TestBogusArguments() TokenizerFactory("Classic", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -180,7 +180,7 @@ public virtual void TestBogusArguments() TokenizerFactory("Whitespace", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -190,7 +190,7 @@ public virtual void TestBogusArguments() TokenizerFactory("Letter", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -200,7 +200,7 @@ public virtual void TestBogusArguments() TokenizerFactory("LowerCase", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -210,7 +210,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("ASCIIFolding", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -220,7 +220,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("Standard", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -230,7 +230,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("Classic", "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/Standard/TestUAX29URLEmailTokenizerFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Standard/TestUAX29URLEmailTokenizerFactory.cs index 2b1e3d6953..773ee89943 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Standard/TestUAX29URLEmailTokenizerFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Standard/TestUAX29URLEmailTokenizerFactory.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; @@ -134,7 +134,7 @@ public virtual void TestBogusArguments() TokenizerFactory("UAX29URLEmail", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -148,7 +148,7 @@ public virtual void TestIllegalArguments() TokenizerFactory("UAX29URLEmail", "maxTokenLength", "-1").Create(new StringReader("hello")); fail(); } - catch (ArgumentException expected) + catch (ArgumentOutOfRangeException expected) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { assertTrue(expected.Message.Contains("maxTokenLength must be greater than zero")); } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Sv/TestSwedishLightStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Sv/TestSwedishLightStemFilterFactory.cs index 4f27eb9f4f..6cde52f369 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Sv/TestSwedishLightStemFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Sv/TestSwedishLightStemFilterFactory.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("SwedishLightStem", "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/Synonym/TestSolrSynonymParser.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSolrSynonymParser.cs index 0d5e2d41d5..2269a671d7 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSolrSynonymParser.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSolrSynonymParser.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using Lucene.Net.Analysis.En; using NUnit.Framework; using System; @@ -63,7 +63,15 @@ public virtual void TestInvalidDoubleMap() { string testFile = "a => b => c"; SolrSynonymParser parser = new SolrSynonymParser(true, true, new MockAnalyzer(Random)); - Assert.Throws(() => parser.Parse(new StringReader(testFile))); + try + { + parser.Parse(new StringReader(testFile)); + fail(); + } + catch (Exception pe) when (pe.IsParseException()) + { + // expected + } } /// @@ -73,7 +81,15 @@ public virtual void TestInvalidAnalyzesToNothingOutput() { string testFile = "a => 1"; SolrSynonymParser parser = new SolrSynonymParser(true, true, new MockAnalyzer(Random, MockTokenizer.SIMPLE, false)); - Assert.Throws(() => parser.Parse(new StringReader(testFile))); + try + { + parser.Parse(new StringReader(testFile)); + fail(); + } + catch (Exception pe) when (pe.IsParseException()) + { + // expected + } } /// @@ -83,7 +99,15 @@ public virtual void TestInvalidAnalyzesToNothingInput() { string testFile = "1 => a"; SolrSynonymParser parser = new SolrSynonymParser(true, true, new MockAnalyzer(Random, MockTokenizer.SIMPLE, false)); - Assert.Throws(() => parser.Parse(new StringReader(testFile))); + try + { + parser.Parse(new StringReader(testFile)); + fail(); + } + catch (Exception pe) when (pe.IsParseException()) + { + // expected + } } /// @@ -93,7 +117,15 @@ public virtual void TestInvalidPositionsInput() { string testFile = "testola => the test"; SolrSynonymParser parser = new SolrSynonymParser(true, true, new EnglishAnalyzer(TEST_VERSION_CURRENT)); - Assert.Throws(() => parser.Parse(new StringReader(testFile))); + try + { + parser.Parse(new StringReader(testFile)); + fail(); + } + catch (Exception pe) when (pe.IsParseException()) + { + // expected + } } /// @@ -103,7 +135,15 @@ public virtual void TestInvalidPositionsOutput() { string testFile = "the test => testola"; SolrSynonymParser parser = new SolrSynonymParser(true, true, new EnglishAnalyzer(TEST_VERSION_CURRENT)); - Assert.Throws(() => parser.Parse(new StringReader(testFile))); + try + { + parser.Parse(new StringReader(testFile)); + fail(); + } + catch (Exception pe) when (pe.IsParseException()) + { + // expected + } } /// diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymFilterFactory.cs index 27c8ab5e54..0bfeab285f 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymFilterFactory.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using Lucene.Net.Analysis.Pattern; using Lucene.Net.Analysis.Util; using NUnit.Framework; @@ -117,7 +117,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("Synonym", "synonyms", "synonyms.txt", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -161,7 +161,7 @@ protected internal virtual void DoTestTokenizerFactoryArguments(Version ver, Typ factory = TokenFilterFactory("Synonym", ver, "synonyms", "synonyms.txt", "tokenizerFactory", clazz); fail("tokenizerFactory should have complained about missing pattern arg"); } - catch (Exception) + catch (Exception expected) when (expected.IsException()) { // :NOOP: } @@ -172,7 +172,7 @@ protected internal virtual void DoTestTokenizerFactoryArguments(Version ver, Typ factory = TokenFilterFactory("Synonym", ver, "synonyms", "synonyms.txt", "tokenizerFactory", clazz, "tokenizerFactory.pattern", "(.*)", "tokenizerFactory.bogusbogusbogus", "bogus", "tokenizerFactory.group", "0"); fail("tokenizerFactory should have complained about missing pattern arg"); } - catch (Exception) + catch (Exception expected) when (expected.IsException()) { // :NOOP: } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymMap.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymMap.cs index 89e88faccb..62065adffb 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymMap.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymMap.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using Lucene.Net.Analysis.NGram; using Lucene.Net.Analysis.Util; using Lucene.Net.Util; @@ -43,7 +43,7 @@ public virtual void TestInvalidMappingRules() SlowSynonymFilterFactory.ParseRules(rules, synMap, "=>", ",", true, null); fail("IllegalArgumentException must be thrown."); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { } } @@ -295,19 +295,19 @@ private sealed class ResourceLoaderAnonymousClass : IResourceLoader { public T NewInstance(string cname) { - throw new Exception("stub"); + throw RuntimeException.Create("stub"); } public Type FindType(string cname) { - throw new Exception("stub"); + throw RuntimeException.Create("stub"); } public Stream OpenResource(string resource) { if (!"something.txt".Equals(resource, StringComparison.Ordinal)) { - throw new Exception("should not get a differnt resource"); + throw RuntimeException.Create("should not get a differnt resource"); } else { diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymMapFilter.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymMapFilter.cs index d840c7ca42..625055ebe0 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymMapFilter.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Synonym/TestSynonymMapFilter.cs @@ -961,10 +961,10 @@ public virtual void TestEmpty() new SynonymFilter(tokenizer, (new SynonymMap.Builder(true)).Build(), true); fail("did not hit expected exception"); } - catch (ArgumentException iae) + catch (ArgumentNullException iae) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { // expected - assertEquals("fst must be non-null", iae.Message); + assertTrue(iae.Message.Contains("fst must be non-null")); // LUCENENET: .NET Adds the parameter name to the message } } } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiAnalyzer.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiAnalyzer.cs index 2f7eb79a40..218abd179a 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiAnalyzer.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiAnalyzer.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 #if FEATURE_BREAKITERATOR using J2N.Threading; using Lucene.Net.Analysis.Core; @@ -215,9 +215,7 @@ public virtual void TestConcurrency() { t.Join(); } -#pragma warning disable 168 - catch (ThreadInterruptedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsInterruptedException()) { fail("Thread interrupted"); } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiTokenizerFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiTokenizerFactory.cs index 0f501ae994..28f0c3362d 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiTokenizerFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiTokenizerFactory.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.Util; using NUnit.Framework; @@ -60,7 +60,7 @@ public virtual void TestBogusArguments() TokenizerFactory("Thai", "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/Th/TestThaiWordFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiWordFilterFactory.cs index 93d60ecc36..fa6a5d1c20 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiWordFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Th/TestThaiWordFilterFactory.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.Util; using NUnit.Framework; @@ -63,7 +63,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("ThaiWord", "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/Tr/TestApostropheFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Tr/TestApostropheFilterFactory.cs index 05fefebe31..f20dae0e21 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Tr/TestApostropheFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Tr/TestApostropheFilterFactory.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("Apostrophe", "bogusArg", "bogusValue"); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameter(s):")); } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Tr/TestTurkishLowerCaseFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Tr/TestTurkishLowerCaseFilterFactory.cs index 6f1fa9f2fc..940794088e 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Tr/TestTurkishLowerCaseFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Tr/TestTurkishLowerCaseFilterFactory.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("TurkishLowerCase", "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/Util/BaseTokenStreamFactoryTestCase.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/BaseTokenStreamFactoryTestCase.cs index 9335688ea3..459bd68603 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/BaseTokenStreamFactoryTestCase.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/BaseTokenStreamFactoryTestCase.cs @@ -1,10 +1,11 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; +using System.Runtime.ExceptionServices; using Lucene.Net.Util; using Version = Lucene.Net.Util.LuceneVersion; @@ -75,12 +76,12 @@ private AbstractAnalysisFactory AnalysisFactory(Type clazz, Version matchVersion { factory = (AbstractAnalysisFactory)Activator.CreateInstance(clazz, args); } - catch (TargetInvocationException e) + catch (Exception e) when (e.IsInvocationTargetException()) { // to simplify tests that check for illegal parameters if (e.InnerException is ArgumentException argumentException) { - throw argumentException; + ExceptionDispatchInfo.Capture(argumentException).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } else { diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/StringMockResourceLoader.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/StringMockResourceLoader.cs index 6f55170f9b..e4833908db 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/StringMockResourceLoader.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/StringMockResourceLoader.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using System; using System.IO; using System.Text; @@ -39,9 +39,9 @@ public Type FindType(string cname) { return Type.GetType(cname); } - 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); } } @@ -52,9 +52,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.Tests.Analysis.Common/Analysis/Util/TestAnalysisSPILoader.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestAnalysisSPILoader.cs index 4cbebf244d..9e51aef9f2 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestAnalysisSPILoader.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestAnalysisSPILoader.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using Lucene.Net.Analysis.CharFilters; using Lucene.Net.Analysis.Core; using Lucene.Net.Analysis.Miscellaneous; @@ -59,7 +59,7 @@ public virtual void TestBogusLookupTokenizer() TokenizerFactory.ForName("sdfsdfsdfdsfsdfsdf", new Dictionary()); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -69,7 +69,7 @@ public virtual void TestBogusLookupTokenizer() TokenizerFactory.ForName("!(**#$U*#$*", new Dictionary()); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -91,7 +91,7 @@ public virtual void TestBogusLookupTokenizerClass() TokenizerFactory.LookupClass("sdfsdfsdfdsfsdfsdf"); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -101,7 +101,7 @@ public virtual void TestBogusLookupTokenizerClass() TokenizerFactory.LookupClass("!(**#$U*#$*"); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -133,7 +133,7 @@ public virtual void TestBogusLookupTokenFilter() TokenFilterFactory.ForName("sdfsdfsdfdsfsdfsdf", new Dictionary()); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -143,7 +143,7 @@ public virtual void TestBogusLookupTokenFilter() TokenFilterFactory.ForName("!(**#$U*#$*", new Dictionary()); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -169,7 +169,7 @@ public virtual void TestBogusLookupTokenFilterClass() TokenFilterFactory.LookupClass("sdfsdfsdfdsfsdfsdf"); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -179,7 +179,7 @@ public virtual void TestBogusLookupTokenFilterClass() TokenFilterFactory.LookupClass("!(**#$U*#$*"); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -208,7 +208,7 @@ public virtual void TestBogusLookupCharFilter() CharFilterFactory.ForName("sdfsdfsdfdsfsdfsdf", new Dictionary()); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -218,7 +218,7 @@ public virtual void TestBogusLookupCharFilter() CharFilterFactory.ForName("!(**#$U*#$*", new Dictionary()); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -240,7 +240,7 @@ public virtual void TestBogusLookupCharFilterClass() CharFilterFactory.LookupClass("sdfsdfsdfdsfsdfsdf"); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } @@ -250,7 +250,7 @@ public virtual void TestBogusLookupCharFilterClass() CharFilterFactory.LookupClass("!(**#$U*#$*"); fail(); } - catch (ArgumentException) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestBufferedCharFilter.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestBufferedCharFilter.cs index 171970984e..f99c02b2ea 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestBufferedCharFilter.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestBufferedCharFilter.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 // https://svn.apache.org/repos/asf/harmony/enhanced/java/trunk/ @@ -105,9 +105,7 @@ public void Test_Close() br.Read(); fail("Read on closed stream"); } -#pragma warning disable 168 - catch (IOException x) -#pragma warning restore 168 + catch (Exception x) when (x.IsIOException()) { return; } @@ -142,9 +140,7 @@ public void Test_MarkI() fail("Failed to invalidate mark properly"); } -#pragma warning disable 168 - catch (IOException x) -#pragma warning restore 168 + catch (Exception x) when (x.IsIOException()) { // Expected } @@ -227,9 +223,7 @@ public void Test_Read() new char[] { '\u8765' }))); assertTrue("Wrong double byte character", br.Read() == '\u8765'); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { fail("Exception during read test"); } @@ -252,9 +246,8 @@ public void Test_Read() assertEquals("Wrong chars", 15, @in.Read()); // Check next byte } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - fail("Exception during read test 2:" + e); } @@ -331,7 +324,7 @@ public void Test_ReadCII() fail("null buffer reading zero bytes should throw NPE"); } #pragma warning disable 168 - catch (NullReferenceException e) + catch (ArgumentNullException e) // LUCENENET specific - changed from NullPointerException to ArgumentNullException #pragma warning restore 168 { //expected @@ -341,7 +334,7 @@ public void Test_ReadCII() { toRet.Dispose(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { fail("unexpected 1: " + e); @@ -353,9 +346,7 @@ public void Test_ReadCII() fail("null buffer reading zero bytes on closed stream should throw IOException"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { //expected } @@ -367,9 +358,7 @@ public void Test_ReadCII() fail("Reading zero bytes on a closed reader should not work"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // expected } @@ -386,9 +375,7 @@ public void Test_ReadCII() fail("IOException should have been thrown"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // expected } @@ -412,7 +399,7 @@ public void Test_ReadCII() assertEquals("Reading zero bytes at EOF should work", 0, toRet .Read(ca, 0, 0)); } - catch (IOException ex) + catch (Exception ex) when (ex.IsIOException()) { fail("Unexpected IOException : " + ex.ToString()); @@ -428,9 +415,7 @@ public void Test_ReadCII() assertTrue("Chars read improperly", new string(buf, 50, 500) .Equals(testString.Substring(0, 500 - 0), StringComparison.Ordinal)); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { fail("Exception during read test"); @@ -478,7 +463,7 @@ public void Test_ReadCII() assertTrue("Incorrect result: " + result, result == 1); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { fail("Unexpected: " + e); @@ -506,7 +491,7 @@ public void Test_ReadCII() fail("Assert 0: NullPointerException expected"); } #pragma warning disable 168 - catch (NullReferenceException e) + catch (ArgumentNullException e) // LUCENENET specific - changed from NullPointerException to ArgumentNullException #pragma warning restore 168 { // Expected @@ -520,9 +505,7 @@ public void Test_ReadCII() reader.Read(null, 1, 0); fail("Assert 1: IOException expected"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // Expected } @@ -534,9 +517,7 @@ public void Test_ReadCII() reader.Read(ch, 0, 42); fail("Assert 2: IOException expected"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // expected } @@ -585,7 +566,7 @@ public void Test_Read_CII_Exception() fail("should throw NullPointerException"); } #pragma warning disable 168 - catch (NullReferenceException e) + catch (ArgumentNullException e) // LUCENENET specific - changed from NullPointerException to ArgumentNullException #pragma warning restore 168 { // expected @@ -598,7 +579,7 @@ public void Test_Read_CII_Exception() fail("should throw NullPointerException"); } #pragma warning disable 168 - catch (NullReferenceException e) + catch (ArgumentNullException e) // LUCENENET specific - changed from NullPointerException to ArgumentNullException #pragma warning restore 168 { // expected @@ -611,7 +592,7 @@ public void Test_Read_CII_Exception() fail("should throw NullPointerException"); } #pragma warning disable 168 - catch (NullReferenceException e) + catch (ArgumentNullException e) // LUCENENET specific - changed from NullPointerException to ArgumentNullException #pragma warning restore 168 { // expected @@ -681,9 +662,7 @@ public void Test_Read_CII_Exception() fail("should throw IOException"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // expected } @@ -694,9 +673,7 @@ public void Test_Read_CII_Exception() fail("should throw IOException"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // expected } @@ -707,9 +684,7 @@ public void Test_Read_CII_Exception() fail("should throw IOException"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // expected } @@ -728,9 +703,7 @@ public void Test_ReadLine() assertEquals("readLine returned incorrect string", "Test_All_Tests", r ); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { fail("Exception during readLine test"); } @@ -747,7 +720,7 @@ public void Test_Ready() br = new BufferedCharFilter(new StringReader(testString)); assertTrue("IsReady returned false", br.IsReady); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { fail("Exception during ready test" + e.toString()); } @@ -771,9 +744,7 @@ public void Test_Reset() assertTrue("Failed to reset properly", testString.Substring(500, 1000 - 500).Equals(new string(buf, 0, 500), StringComparison.Ordinal)); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { fail("Exception during reset test"); } @@ -784,9 +755,7 @@ public void Test_Reset() br.Reset(); fail("Reset succeeded on unmarked stream"); } -#pragma warning disable 168 - catch (IOException x) -#pragma warning restore 168 + catch (Exception x) when (x.IsIOException()) { return; @@ -810,9 +779,7 @@ public void Test_Reset_IOException() br.Reset(); fail("should throw IOException"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // Expected } @@ -850,9 +817,7 @@ public void Test_SkipJ() assertTrue("Failed to set skip properly", testString.Substring(500, 1000 - 500).Equals(new string(buf, 0, 500), StringComparison.Ordinal)); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { fail("Exception during skip test"); } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArrayIterator.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArrayIterator.cs index 331cf05309..908fafe1e4 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArrayIterator.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArrayIterator.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 #if FEATURE_BREAKITERATOR using System; using Lucene.Net.Util; @@ -159,7 +159,7 @@ private void DoTests(CharArrayIterator ci) ci.SetIndex(5); fail(); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { assertTrue(e is ArgumentException); } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArrayMap.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArrayMap.cs index 6521ee2586..40637eade4 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArrayMap.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArrayMap.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.Support; using Lucene.Net.Util; @@ -109,7 +109,7 @@ public virtual void TestMethods() cs.Add("test"); fail("keySet() allows adding new keys"); } - catch (NotSupportedException) + catch (Exception ue) when (ue.IsUnsupportedOperationException()) { // pass } @@ -178,7 +178,7 @@ public void TestModifyOnUnmodifiable() map.Put(NOT_IN_MAP.ToCharArray(), 3); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable map", map.ContainsKey(NOT_IN_MAP)); @@ -191,7 +191,7 @@ public void TestModifyOnUnmodifiable() map.Put(NOT_IN_MAP, 3); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable map", map.ContainsKey(NOT_IN_MAP)); @@ -204,7 +204,7 @@ public void TestModifyOnUnmodifiable() map.Put(new StringBuilder(NOT_IN_MAP), 3); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable map", map.ContainsKey(NOT_IN_MAP)); @@ -212,13 +212,13 @@ public void TestModifyOnUnmodifiable() assertEquals("Size of unmodifiable map has changed", size, map.Count); } - #region Added for better .NET support + #region LUCENENET Added for better .NET support try { map.Add(NOT_IN_MAP, 3); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable map", map.ContainsKey(NOT_IN_MAP)); @@ -231,7 +231,7 @@ public void TestModifyOnUnmodifiable() map.Add(new KeyValuePair(NOT_IN_MAP, 3)); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable map", map.ContainsKey(NOT_IN_MAP)); @@ -244,7 +244,7 @@ public void TestModifyOnUnmodifiable() map[new StringBuilder(NOT_IN_MAP)] = 3; fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable map", map.ContainsKey(NOT_IN_MAP)); @@ -259,19 +259,19 @@ public void TestModifyOnUnmodifiable() #pragma warning restore 612, 618 fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertEquals("Size of unmodifiable map has changed", size, map.Count); } - #endregion + #endregion LUCENENET Added for better .NET support try { map.Clear(); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertEquals("Size of unmodifiable map has changed", size, map.size()); @@ -282,7 +282,7 @@ public void TestModifyOnUnmodifiable() map.EntrySet().Clear(); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertEquals("Size of unmodifiable map has changed", size, map.size()); @@ -293,7 +293,7 @@ public void TestModifyOnUnmodifiable() map.Keys.Clear(); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertEquals("Size of unmodifiable map has changed", size, map.size()); @@ -304,7 +304,7 @@ public void TestModifyOnUnmodifiable() map.Put((object)NOT_IN_MAP, 3); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable map", map.ContainsKey(NOT_IN_MAP)); @@ -317,7 +317,7 @@ public void TestModifyOnUnmodifiable() map.PutAll(Collections.SingletonMap(NOT_IN_MAP, 3)); fail("Modified unmodifiable map"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable map", map.ContainsKey(NOT_IN_MAP)); diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArraySet.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArraySet.cs index 4d61789746..1147fad7d3 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArraySet.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharArraySet.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.Attributes; using Lucene.Net.Util; @@ -120,7 +120,7 @@ public virtual void TestModifyOnUnmodifiable() set.Add(NOT_IN_SET.ToCharArray()); fail("Modified unmodifiable set"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET)); @@ -132,7 +132,7 @@ public virtual void TestModifyOnUnmodifiable() set.add(NOT_IN_SET); fail("Modified unmodifiable set"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET)); @@ -144,7 +144,7 @@ public virtual void TestModifyOnUnmodifiable() set.Add(new StringBuilder(NOT_IN_SET)); fail("Modified unmodifiable set"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET)); @@ -156,7 +156,7 @@ public virtual void TestModifyOnUnmodifiable() set.clear(); fail("Modified unmodifiable set"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Changed unmodifiable set", set.contains(NOT_IN_SET)); @@ -167,7 +167,7 @@ public virtual void TestModifyOnUnmodifiable() set.add(NOT_IN_SET); fail("Modified unmodifiable set"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET)); @@ -184,13 +184,13 @@ public virtual void TestModifyOnUnmodifiable() // set.removeAll(new CharArraySet(TEST_VERSION_CURRENT, TEST_STOP_WORDS, true)); // fail("Modified unmodifiable set"); //} - //catch (NotSupportedException) + //catch (Exception e) when (e.IsUnsupportedOperationException()) //{ // // expected // assertEquals("Size of unmodifiable set has changed", size, set.size()); //} - #region Added for better .NET support + #region LUCENENET Added for better .NET support // This test was added for .NET to check the Remove method, since the extension method // above fails to execute. try @@ -200,42 +200,43 @@ public virtual void TestModifyOnUnmodifiable() #pragma warning restore 612, 618 fail("Modified unmodifiable set"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertEquals("Size of unmodifiable set has changed", size, set.size()); } - #endregion + // LUCENENET Specific - added to test .NETified UnionWith method try { - set.retainAll(new CharArraySet(TEST_VERSION_CURRENT, new [] { NOT_IN_SET }, true)); + set.UnionWith(new[] { NOT_IN_SET }); fail("Modified unmodifiable set"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected - assertEquals("Size of unmodifiable set has changed", size, set.size()); + assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET)); } + #endregion LUCENENET Added for better .NET support + try { - set.addAll(new[] { NOT_IN_SET}); + set.retainAll(new CharArraySet(TEST_VERSION_CURRENT, new [] { NOT_IN_SET }, true)); fail("Modified unmodifiable set"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected - assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET)); + assertEquals("Size of unmodifiable set has changed", size, set.size()); } - // LUCENENET Specific - added to test .NETified UnionWith method try { - set.UnionWith(new[] { NOT_IN_SET }); + set.addAll(new[] { NOT_IN_SET}); fail("Modified unmodifiable set"); } - catch (NotSupportedException) + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET)); diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharacterUtils.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharacterUtils.cs index 7e093cc506..1b35a9e73e 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharacterUtils.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestCharacterUtils.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using J2N; using Lucene.Net.Support; using Lucene.Net.Util; @@ -47,7 +47,7 @@ public virtual void TestCodePointAtCharSequenceInt() java4.CodePointAt(highSurrogateAt3, 4); fail("string index out of bounds"); } - catch (ArgumentOutOfRangeException) + catch (Exception e) when (e.IsIndexOutOfBoundsException()) { } @@ -60,7 +60,7 @@ public virtual void TestCodePointAtCharSequenceInt() java5.CodePointAt(highSurrogateAt3, 4); fail("string index out of bounds"); } - catch (ArgumentOutOfRangeException) + catch (Exception e) when (e.IsIndexOutOfBoundsException()) { } @@ -110,7 +110,7 @@ public virtual void TestOffsetByCodePoint() var to = java4.OffsetByCodePoints(s, 0, s.Length, index, offset); assertEquals(to, index + offset); } - catch (ArgumentOutOfRangeException) + catch (Exception e) when (e.IsIndexOutOfBoundsException()) { assertTrue((index + offset) < 0 || (index + offset) > s.Length); } @@ -120,14 +120,14 @@ public virtual void TestOffsetByCodePoint() { o = java5.OffsetByCodePoints(s, 0, s.Length, index, offset); } - catch (ArgumentOutOfRangeException) + catch (Exception e) when (e.IsIndexOutOfBoundsException()) { try { Character.OffsetByCodePoints(s, 0, s.Length, index, offset); fail(); } - catch (ArgumentOutOfRangeException) + catch (Exception e2) when (e2.IsIndexOutOfBoundsException()) { // OK } @@ -184,7 +184,7 @@ public virtual void TestNewCharacterBuffer() CharacterUtils.NewCharacterBuffer(1); fail("length must be >= 2"); } - catch (ArgumentException) + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { } } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestElisionFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestElisionFilterFactory.cs index cc4fb007fb..6852c79f9c 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestElisionFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestElisionFilterFactory.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using NUnit.Framework; using System; using System.IO; @@ -73,7 +73,7 @@ public virtual void TestBogusArguments() TokenFilterFactory("Elision", "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/Util/TestFilesystemResourceLoader.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestFilesystemResourceLoader.cs index fedf943c8c..06db2c28ef 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestFilesystemResourceLoader.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Util/TestFilesystemResourceLoader.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using J2N; using Lucene.Net.Util; using NUnit.Framework; @@ -35,16 +35,16 @@ private void assertNotFound(IResourceLoader rl) IOUtils.DisposeWhileHandlingException(rl.OpenResource("/this-directory-really-really-really-should-not-exist/foo/bar.txt")); fail("The resource does not exist, should fail!"); } - catch (IOException) + catch (Exception ioe) when (ioe.IsIOException()) { // pass } try { - rl.NewInstance("org.apache.lucene.analysis.FooBarFilterFactory"); + rl.NewInstance("org.apache.lucene.analysis.FooBarFilterFactory"); // LUCENENET TODO: This test is invalid because this type name doesn't work in .NET fail("The class does not exist, should fail!"); } - catch (Exception) + catch (Exception iae) when (iae.IsRuntimeException()) { // pass } diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Wikipedia/TestWikipediaTokenizerFactory.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Wikipedia/TestWikipediaTokenizerFactory.cs index 33cf61d17f..50ce7e3fe4 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Wikipedia/TestWikipediaTokenizerFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Wikipedia/TestWikipediaTokenizerFactory.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; @@ -46,7 +46,7 @@ public virtual void TestBogusArguments() TokenizerFactory("Wikipedia", "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/Lucene.Net.Tests.Analysis.Common.csproj b/src/Lucene.Net.Tests.Analysis.Common/Lucene.Net.Tests.Analysis.Common.csproj index b4b3e9acc8..c8763c53ab 100644 --- a/src/Lucene.Net.Tests.Analysis.Common/Lucene.Net.Tests.Analysis.Common.csproj +++ b/src/Lucene.Net.Tests.Analysis.Common/Lucene.Net.Tests.Analysis.Common.csproj @@ -51,6 +51,10 @@ + + + + diff --git a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestCharArrayIterator.cs b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestCharArrayIterator.cs index fa76033765..a5dbad9972 100644 --- a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestCharArrayIterator.cs +++ b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestCharArrayIterator.cs @@ -107,7 +107,7 @@ public void TestSetIndex() ci.SetIndex(5); fail(); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { assertTrue(e is ArgumentException); } diff --git a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestICUTokenizer.cs b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestICUTokenizer.cs index 23b6f213ca..2a40b41e9c 100644 --- a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestICUTokenizer.cs +++ b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestICUTokenizer.cs @@ -386,9 +386,9 @@ public override void Run() } } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestICUTokenizerFactory.cs b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestICUTokenizerFactory.cs index d24bc1c165..3fa04f4fd7 100644 --- a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestICUTokenizerFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/Segmentation/TestICUTokenizerFactory.cs @@ -106,7 +106,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUFoldingFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUFoldingFilterFactory.cs index 1f60596569..fadc3c8ecc 100644 --- a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUFoldingFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUFoldingFilterFactory.cs @@ -1,4 +1,4 @@ -// Lucene version compatibility level 4.8.1 +// Lucene version compatibility level 4.8.1 using NUnit.Framework; using System; using System.Collections.Generic; @@ -51,7 +51,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUNormalizer2CharFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUNormalizer2CharFilterFactory.cs index 4f715c8ffc..73c92d244f 100644 --- a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUNormalizer2CharFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUNormalizer2CharFilterFactory.cs @@ -50,7 +50,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUNormalizer2FilterFactory.cs b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUNormalizer2FilterFactory.cs index c03ffb5c48..004e338a9a 100644 --- a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUNormalizer2FilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUNormalizer2FilterFactory.cs @@ -50,7 +50,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUTransformFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUTransformFilterFactory.cs index 9f216e301a..0e78cb2c36 100644 --- a/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUTransformFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.ICU/Analysis/Icu/TestICUTransformFilterFactory.cs @@ -89,7 +89,7 @@ public void TestBogusArguments() fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.ICU/Collation/TestICUCollationKeyFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.ICU/Collation/TestICUCollationKeyFilterFactory.cs index 9223bcc2d4..88c9957666 100644 --- a/src/Lucene.Net.Tests.Analysis.ICU/Collation/TestICUCollationKeyFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.ICU/Collation/TestICUCollationKeyFilterFactory.cs @@ -12,6 +12,7 @@ using System.Collections.Generic; using System.IO; using System.Reflection; +using System.Runtime.ExceptionServices; using System.Text; namespace Lucene.Net.Collation @@ -325,12 +326,12 @@ private TokenFilterFactory tokenFilterFactory(String name, params String[] keysA //factory = clazz.getConstructor(Map.class).newInstance(args); factory = (TokenFilterFactory)Activator.CreateInstance(clazz, args); } - catch (TargetInvocationException e) + catch (Exception e) when (e.IsInvocationTargetException()) { // to simplify tests that check for illegal parameters - if (e.InnerException is ArgumentException) + if (e.InnerException is ArgumentException argumentException) { - throw (ArgumentException)e.InnerException; + ExceptionDispatchInfo.Capture(argumentException).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } else { diff --git a/src/Lucene.Net.Tests.Analysis.Kuromoji/StringMockResourceLoader.cs b/src/Lucene.Net.Tests.Analysis.Kuromoji/StringMockResourceLoader.cs index 49819cdd20..7fd3944784 100644 --- a/src/Lucene.Net.Tests.Analysis.Kuromoji/StringMockResourceLoader.cs +++ b/src/Lucene.Net.Tests.Analysis.Kuromoji/StringMockResourceLoader.cs @@ -39,9 +39,9 @@ public virtual Type FindType(String cname) //return Class.forName(cname).asSubclass(expectedType); return Type.GetType(cname); } - 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); } } @@ -55,7 +55,7 @@ public virtual T NewInstance(String cname) } catch (Exception e) { - throw new Exception("Cannot create instance: " + cname, e); + throw RuntimeException.Create("Cannot create instance: " + cname, e); } } diff --git a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseBaseFormFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseBaseFormFilterFactory.cs index 61a8b2e69c..afdfc004ac 100644 --- a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseBaseFormFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseBaseFormFilterFactory.cs @@ -51,7 +51,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseIterationMarkCharFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseIterationMarkCharFilterFactory.cs index 88f71a9321..8310d1d781 100644 --- a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseIterationMarkCharFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseIterationMarkCharFilterFactory.cs @@ -99,7 +99,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseKatakanaStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseKatakanaStemFilterFactory.cs index 49ac181dd1..eda816e6c2 100644 --- a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseKatakanaStemFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseKatakanaStemFilterFactory.cs @@ -53,7 +53,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapanesePartOfSpeechStopFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapanesePartOfSpeechStopFilterFactory.cs index 617a1b8769..afe26cf8ba 100644 --- a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapanesePartOfSpeechStopFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapanesePartOfSpeechStopFilterFactory.cs @@ -61,7 +61,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseReadingFormFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseReadingFormFilterFactory.cs index 053652b65e..1c5f051009 100644 --- a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseReadingFormFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseReadingFormFilterFactory.cs @@ -50,7 +50,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseTokenizer.cs b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseTokenizer.cs index 0d13094114..0e0cad9298 100644 --- a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseTokenizer.cs +++ b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseTokenizer.cs @@ -37,7 +37,7 @@ public static UserDictionary ReadDict() Stream @is = typeof(TestJapaneseTokenizer).getResourceAsStream("userdict.txt"); if (@is == null) { - throw new Exception("Cannot find userdict.txt in test classpath!"); + throw RuntimeException.Create("Cannot find userdict.txt in test classpath!"); } try { @@ -51,9 +51,9 @@ public static UserDictionary ReadDict() @is.Dispose(); } } - 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.Tests.Analysis.Kuromoji/TestJapaneseTokenizerFactory.cs b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseTokenizerFactory.cs index 91fbf1688d..f80a91101a 100644 --- a/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseTokenizerFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseTokenizerFactory.cs @@ -125,7 +125,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.Morfologik/Morfologik/TestMorfologikFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Morfologik/Morfologik/TestMorfologikFilterFactory.cs index c63987244a..47105d2ce4 100644 --- a/src/Lucene.Net.Tests.Analysis.Morfologik/Morfologik/TestMorfologikFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Morfologik/Morfologik/TestMorfologikFilterFactory.cs @@ -35,17 +35,17 @@ private class ForbidResourcesLoader : IResourceLoader { public Type FindType(string cname) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public T NewInstance(string cname) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public Stream OpenResource(string resource) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } diff --git a/src/Lucene.Net.Tests.Analysis.Phonetic/Language/SoundexTest.cs b/src/Lucene.Net.Tests.Analysis.Phonetic/Language/SoundexTest.cs index d05f40e5cd..c2df30d9e3 100644 --- a/src/Lucene.Net.Tests.Analysis.Phonetic/Language/SoundexTest.cs +++ b/src/Lucene.Net.Tests.Analysis.Phonetic/Language/SoundexTest.cs @@ -379,9 +379,7 @@ public void TestUsMappingEWithAcute() Assert.AreEqual("\u00c9000", this.StringEncoder.Encode("\u00e9")); Assert.Fail("Expected IllegalArgumentException not thrown"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -409,9 +407,7 @@ public void TestUsMappingOWithDiaeresis() Assert.AreEqual("\u00d6000", this.StringEncoder.Encode("\u00f6")); Assert.Fail("Expected IllegalArgumentException not thrown"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests.Analysis.Phonetic/TestBeiderMorseFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Phonetic/TestBeiderMorseFilterFactory.cs index 5bdf1b79db..c5583b2361 100644 --- a/src/Lucene.Net.Tests.Analysis.Phonetic/TestBeiderMorseFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Phonetic/TestBeiderMorseFilterFactory.cs @@ -80,7 +80,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.Phonetic/TestDoubleMetaphoneFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Phonetic/TestDoubleMetaphoneFilterFactory.cs index 5ba337b06e..8742066eb2 100644 --- a/src/Lucene.Net.Tests.Analysis.Phonetic/TestDoubleMetaphoneFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Phonetic/TestDoubleMetaphoneFilterFactory.cs @@ -61,7 +61,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.Phonetic/TestPhoneticFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Phonetic/TestPhoneticFilterFactory.cs index 1baedfba5f..e5027bbf85 100644 --- a/src/Lucene.Net.Tests.Analysis.Phonetic/TestPhoneticFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Phonetic/TestPhoneticFilterFactory.cs @@ -74,7 +74,7 @@ public void TestMissingEncoder() new PhoneticFilterFactory(new Dictionary()); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Configuration Error: missing parameter 'encoder'")); } @@ -90,7 +90,7 @@ public void TestUnknownEncoder() factory.Inform(new ClasspathResourceLoader(factory.GetType())); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Error loading encoder")); } @@ -107,7 +107,7 @@ public void TestUnknownEncoderReflection() factory.Inform(new ClasspathResourceLoader(factory.GetType())); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Error loading encoder")); } @@ -206,7 +206,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.SmartCn/TestHMMChineseTokenizerFactory.cs b/src/Lucene.Net.Tests.Analysis.SmartCn/TestHMMChineseTokenizerFactory.cs index 60f24c9564..901c5a9a86 100644 --- a/src/Lucene.Net.Tests.Analysis.SmartCn/TestHMMChineseTokenizerFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.SmartCn/TestHMMChineseTokenizerFactory.cs @@ -63,7 +63,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.SmartCn/TestSmartChineseFactories.cs b/src/Lucene.Net.Tests.Analysis.SmartCn/TestSmartChineseFactories.cs index 4b23ec1513..f1168659b2 100644 --- a/src/Lucene.Net.Tests.Analysis.SmartCn/TestSmartChineseFactories.cs +++ b/src/Lucene.Net.Tests.Analysis.SmartCn/TestSmartChineseFactories.cs @@ -77,7 +77,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } @@ -89,7 +89,7 @@ public void TestBogusArguments() }); fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { assertTrue(expected.Message.Contains("Unknown parameters")); } diff --git a/src/Lucene.Net.Tests.Analysis.Stempel/Egothor.Stemmer/TestCompile.cs b/src/Lucene.Net.Tests.Analysis.Stempel/Egothor.Stemmer/TestCompile.cs index bc10288171..25e253f17d 100644 --- a/src/Lucene.Net.Tests.Analysis.Stempel/Egothor.Stemmer/TestCompile.cs +++ b/src/Lucene.Net.Tests.Analysis.Stempel/Egothor.Stemmer/TestCompile.cs @@ -1,4 +1,4 @@ -/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -173,11 +173,10 @@ private static void AssertTrie(Trie trie, string file, bool usefull, using TextReader @in = new StreamReader(new FileStream(file, FileMode.Open), Encoding.UTF8); for (string line = @in.ReadLine(); line != null; line = @in.ReadLine()) { - 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) { @@ -201,7 +200,7 @@ private static void AssertTrie(Trie trie, string file, bool usefull, assertEquals(stem.ToLowerInvariant(), stm.ToString().ToLowerInvariant()); } } - catch (InvalidOperationException /*x*/) + 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.Tests.Analysis.Stempel/Stempel/TestStempelPolishStemFilterFactory.cs b/src/Lucene.Net.Tests.Analysis.Stempel/Stempel/TestStempelPolishStemFilterFactory.cs index 317dc4c591..463a467582 100644 --- a/src/Lucene.Net.Tests.Analysis.Stempel/Stempel/TestStempelPolishStemFilterFactory.cs +++ b/src/Lucene.Net.Tests.Analysis.Stempel/Stempel/TestStempelPolishStemFilterFactory.cs @@ -47,7 +47,7 @@ public void TestBogusArguments() new StempelPolishStemFilterFactory(new Dictionary() { { "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.Benchmark/ByTask/Feeds/LineDocSourceTest.cs b/src/Lucene.Net.Tests.Benchmark/ByTask/Feeds/LineDocSourceTest.cs index 7cd27f1a98..28bb6626e6 100644 --- a/src/Lucene.Net.Tests.Benchmark/ByTask/Feeds/LineDocSourceTest.cs +++ b/src/Lucene.Net.Tests.Benchmark/ByTask/Feeds/LineDocSourceTest.cs @@ -240,9 +240,7 @@ public void TestInvalidFormat() doIndexAndSearchTest(file, null, null); fail("Some exception should have been thrown for: [" + testCases[i] + "]"); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { // expected. } diff --git a/src/Lucene.Net.Tests.Benchmark/ByTask/Tasks/WriteLineDocTaskTest.cs b/src/Lucene.Net.Tests.Benchmark/ByTask/Tasks/WriteLineDocTaskTest.cs index 9e994aa472..017d1720b4 100644 --- a/src/Lucene.Net.Tests.Benchmark/ByTask/Tasks/WriteLineDocTaskTest.cs +++ b/src/Lucene.Net.Tests.Benchmark/ByTask/Tasks/WriteLineDocTaskTest.cs @@ -374,7 +374,6 @@ private class ThreadAnonymousClass : ThreadJob public ThreadAnonymousClass(string name, WriteLineDocTask wldt) : base(name) { - this.IsDebug = true; this.wldt = wldt; } @@ -384,9 +383,9 @@ public override void Run() { wldt.DoLogic(); } - 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.Tests.Benchmark/ByTask/TestPerfTasksLogic.cs b/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksLogic.cs index 9176111cfe..8a8d47256f 100644 --- a/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksLogic.cs +++ b/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksLogic.cs @@ -263,9 +263,7 @@ public void TestHighlightingNoTvNoStore() assertTrue("CountingHighlighterTest should have thrown an exception", false); assertNotNull(benchmark); // (avoid compile warning on unused variable) } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { assertTrue(true); } diff --git a/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksParse.cs b/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksParse.cs index 090b636298..5be1307d2f 100644 --- a/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksParse.cs +++ b/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksParse.cs @@ -137,7 +137,7 @@ public void TestParseExamples() if (contentSource != null) { if (Type.GetType(contentSource) == null) - throw new TypeLoadException(contentSource); + throw ClassNotFoundException.Create(contentSource); } config.Set("work.dir", CreateTempDir(LuceneTestCase.GetTestClass().Name).FullName); config.Set("content.source", typeof(MockContentSource).AssemblyQualifiedName); @@ -145,7 +145,7 @@ public void TestParseExamples() if (dir != null) { if (Type.GetType(dir) == null) - throw new TypeLoadException(dir); + throw ClassNotFoundException.Create(dir); } config.Set("directory", typeof(RAMDirectory).AssemblyQualifiedName); if (config.Get("line.file.out", null) != null) @@ -156,16 +156,16 @@ public void TestParseExamples() if (queryMaker != null) { if (Type.GetType(queryMaker) == null) - throw new TypeLoadException(queryMaker); + throw ClassNotFoundException.Create(queryMaker); config.Set("query.maker", typeof(MockQueryMaker).AssemblyQualifiedName); } PerfRunData data = new PerfRunData(config); new Algorithm(data); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { - throw new Exception("Could not parse sample file: " + algFile, t); + throw AssertionError.Create("Could not parse sample file: " + algFile, t); } foundFiles = true; } diff --git a/src/Lucene.Net.Tests.Classification/SimpleNaiveBayesClassifierTest.cs b/src/Lucene.Net.Tests.Classification/SimpleNaiveBayesClassifierTest.cs index 8047d3cc3c..c9c18c76b8 100644 --- a/src/Lucene.Net.Tests.Classification/SimpleNaiveBayesClassifierTest.cs +++ b/src/Lucene.Net.Tests.Classification/SimpleNaiveBayesClassifierTest.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Analysis; +using Lucene.Net.Analysis; using Lucene.Net.Analysis.Core; using Lucene.Net.Analysis.NGram; using Lucene.Net.Analysis.Reverse; @@ -55,7 +55,7 @@ public void TestNGramUsage() private class NGramAnalyzer : Analyzer { - protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) + protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer tokenizer = new KeywordTokenizer(reader); return new TokenStreamComponents(tokenizer, new ReverseStringFilter(TEST_VERSION_CURRENT, new EdgeNGramTokenFilter(TEST_VERSION_CURRENT, new ReverseStringFilter(TEST_VERSION_CURRENT, tokenizer), 10, 20))); diff --git a/src/Lucene.Net.Tests.Classification/Utils/DataSplitterTest.cs b/src/Lucene.Net.Tests.Classification/Utils/DataSplitterTest.cs index 30ed545076..6960a56d9f 100644 --- a/src/Lucene.Net.Tests.Classification/Utils/DataSplitterTest.cs +++ b/src/Lucene.Net.Tests.Classification/Utils/DataSplitterTest.cs @@ -140,13 +140,10 @@ private static void CloseQuietly(IndexReader reader) if (reader != null) reader.Dispose(); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { // do nothing } } } - } \ No newline at end of file diff --git a/src/Lucene.Net.Tests.Expressions/JS/TestCustomFunctions.cs b/src/Lucene.Net.Tests.Expressions/JS/TestCustomFunctions.cs index 055926d3c0..9ca94881c9 100644 --- a/src/Lucene.Net.Tests.Expressions/JS/TestCustomFunctions.cs +++ b/src/Lucene.Net.Tests.Expressions/JS/TestCustomFunctions.cs @@ -41,7 +41,7 @@ public virtual void TestEmpty() JavascriptCompiler.Compile("sqrt(20)", functions); Assert.Fail(); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { Assert.IsTrue(e.Message.Contains("Unrecognized method")); } @@ -116,7 +116,7 @@ public virtual void TestWrongReturnType() JavascriptCompiler.Compile("foo()", functions); Assert.Fail(); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { Assert.IsTrue(e.Message.Contains("does not return a double")); } @@ -135,7 +135,7 @@ public virtual void TestWrongParameterType() JavascriptCompiler.Compile("foo(2)", functions); Assert.Fail(); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { Assert.IsTrue(e.Message.Contains("must take only double parameters")); } @@ -154,7 +154,7 @@ public virtual void TestWrongNotStatic() JavascriptCompiler.Compile("foo()", functions); Assert.Fail(); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { Assert.IsTrue(e.Message.Contains("is not static")); } @@ -174,7 +174,7 @@ public virtual void TestWrongNotPublic() JavascriptCompiler.Compile("foo()", functions); Assert.Fail(); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { Assert.IsTrue(e.Message.Contains("is not public")); } @@ -196,7 +196,7 @@ public virtual void TestWrongNestedNotPublic() JavascriptCompiler.Compile("foo()", functions); Assert.Fail(); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { Assert.IsTrue(e.Message.Contains("is not public")); } @@ -231,7 +231,7 @@ public virtual void TestThrowingException() expr.Evaluate(0, null); Assert.Fail(); } - catch (ArithmeticException e) + catch (Exception e) when (e.IsArithmeticException()) { Assert.AreEqual(MESSAGE, e.Message); StringWriter sw = new StringWriter(); diff --git a/src/Lucene.Net.Tests.Expressions/JS/TestJavascriptCompiler.cs b/src/Lucene.Net.Tests.Expressions/JS/TestJavascriptCompiler.cs index adbbc81228..f933c8111b 100644 --- a/src/Lucene.Net.Tests.Expressions/JS/TestJavascriptCompiler.cs +++ b/src/Lucene.Net.Tests.Expressions/JS/TestJavascriptCompiler.cs @@ -48,7 +48,7 @@ public virtual void TestInvalidNamespaces() JavascriptCompiler.Compile("object.0invalid"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { //expected } @@ -58,7 +58,7 @@ public virtual void TestInvalidNamespaces() JavascriptCompiler.Compile("0.invalid"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { //expected } @@ -68,7 +68,7 @@ public virtual void TestInvalidNamespaces() JavascriptCompiler.Compile("object..invalid"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { //expected } @@ -78,7 +78,7 @@ public virtual void TestInvalidNamespaces() JavascriptCompiler.Compile(".invalid"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { //expected } @@ -92,7 +92,7 @@ public virtual void TestInvalidCompiles() JavascriptCompiler.Compile("100 100"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { // expected } @@ -101,7 +101,7 @@ public virtual void TestInvalidCompiles() JavascriptCompiler.Compile("7*/-8"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { // expected } @@ -111,7 +111,7 @@ public virtual void TestInvalidCompiles() JavascriptCompiler.Compile("0y1234"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { // expected } @@ -121,7 +121,7 @@ public virtual void TestInvalidCompiles() JavascriptCompiler.Compile("500EE"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { // expected } @@ -131,7 +131,7 @@ public virtual void TestInvalidCompiles() JavascriptCompiler.Compile("500.5EE"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { // expected } @@ -145,7 +145,7 @@ public virtual void TestEmpty() JavascriptCompiler.Compile(string.Empty); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { // expected } @@ -155,7 +155,7 @@ public virtual void TestEmpty() JavascriptCompiler.Compile("()"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { // expected } @@ -165,7 +165,7 @@ public virtual void TestEmpty() JavascriptCompiler.Compile(" \r\n \n \t"); Assert.Fail(); } - catch (InvalidOperationException) + catch (Exception expected) when (expected.IsParseException()) { // expected } @@ -179,7 +179,7 @@ public virtual void TestNull() JavascriptCompiler.Compile(null); Assert.Fail(); } - catch (ArgumentNullException) + catch (Exception expected) when (expected.IsNullPointerException()) { // expected } @@ -193,7 +193,7 @@ public virtual void TestWrongArity() JavascriptCompiler.Compile("tan()"); Assert.Fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { Assert.IsTrue(expected.Message.Contains("arguments for method call")); } @@ -203,7 +203,7 @@ public virtual void TestWrongArity() JavascriptCompiler.Compile("tan(1, 1)"); Assert.Fail(); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { Assert.IsTrue(expected.Message.Contains("arguments for method call")); } diff --git a/src/Lucene.Net.Tests.Expressions/TestExpressionValidation.cs b/src/Lucene.Net.Tests.Expressions/TestExpressionValidation.cs index bf3330bcd4..b9cdaf144b 100644 --- a/src/Lucene.Net.Tests.Expressions/TestExpressionValidation.cs +++ b/src/Lucene.Net.Tests.Expressions/TestExpressionValidation.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Expressions.JS; +using Lucene.Net.Expressions.JS; using Lucene.Net.Search; using Lucene.Net.Util; using NUnit.Framework; @@ -55,7 +55,7 @@ public virtual void TestInvalidExternal() bindings.Validate(); Assert.Fail("didn't get expected exception"); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { Assert.IsTrue(expected.Message.Contains("Invalid reference")); } @@ -72,7 +72,7 @@ public virtual void TestInvalidExternal2() bindings.Validate(); Assert.Fail("didn't get expected exception"); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { Assert.IsTrue(expected.Message.Contains("Invalid reference")); } @@ -88,7 +88,7 @@ public virtual void TestSelfRecursion() bindings.Validate(); Assert.Fail("didn't get expected exception"); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { Assert.IsTrue(expected.Message.Contains("Cycle detected")); } @@ -105,7 +105,7 @@ public virtual void TestCoRecursion() bindings.Validate(); Assert.Fail("didn't get expected exception"); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { Assert.IsTrue(expected.Message.Contains("Cycle detected")); } @@ -123,7 +123,7 @@ public virtual void TestCoRecursion2() bindings.Validate(); Assert.Fail("didn't get expected exception"); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { Assert.IsTrue(expected.Message.Contains("Cycle detected")); } @@ -141,7 +141,7 @@ public virtual void TestCoRecursion3() bindings.Validate(); Assert.Fail("didn't get expected exception"); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { Assert.IsTrue(expected.Message.Contains("Cycle detected")); } @@ -160,7 +160,7 @@ public virtual void TestCoRecursion4() bindings.Validate(); Assert.Fail("didn't get expected exception"); } - catch (ArgumentException expected) + catch (Exception expected) when (expected.IsIllegalArgumentException()) { Assert.IsTrue(expected.Message.Contains("Cycle detected")); } diff --git a/src/Lucene.Net.Tests.Facet/AssertingSubDocsAtOnceCollector.cs b/src/Lucene.Net.Tests.Facet/AssertingSubDocsAtOnceCollector.cs index a8c1e3d29d..d64d1a6796 100644 --- a/src/Lucene.Net.Tests.Facet/AssertingSubDocsAtOnceCollector.cs +++ b/src/Lucene.Net.Tests.Facet/AssertingSubDocsAtOnceCollector.cs @@ -58,7 +58,7 @@ public virtual void Collect(int docID) { if (docID != s.DocID) { - throw new InvalidOperationException("subScorer=" + s + " has docID=" + s.DocID + " != collected docID=" + docID); + throw IllegalStateException.Create("subScorer=" + s + " has docID=" + s.DocID + " != collected docID=" + docID); } } } diff --git a/src/Lucene.Net.Tests.Facet/Range/TestRangeFacetCounts.cs b/src/Lucene.Net.Tests.Facet/Range/TestRangeFacetCounts.cs index 71142ab914..d0ada3e1a9 100644 --- a/src/Lucene.Net.Tests.Facet/Range/TestRangeFacetCounts.cs +++ b/src/Lucene.Net.Tests.Facet/Range/TestRangeFacetCounts.cs @@ -121,7 +121,7 @@ public virtual void TestUselessRange() _ = new Int64Range("useless", 7, true, 6, true); fail("did not hit expected exception"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -130,7 +130,7 @@ public virtual void TestUselessRange() _ = new Int64Range("useless", 7, true, 7, false); fail("did not hit expected exception"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -139,7 +139,7 @@ public virtual void TestUselessRange() _ = new DoubleRange("useless", 7.0, true, 6.0, true); fail("did not hit expected exception"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -148,7 +148,7 @@ public virtual void TestUselessRange() _ = new DoubleRange("useless", 7.0, true, 7.0, false); fail("did not hit expected exception"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -1191,17 +1191,17 @@ public override double DoubleVal(int doc) public override bool Equals(object o) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override int GetHashCode() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override string GetDescription() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } diff --git a/src/Lucene.Net.Tests.Facet/SlowRAMDirectory.cs b/src/Lucene.Net.Tests.Facet/SlowRAMDirectory.cs index d333fb8823..10affacb41 100644 --- a/src/Lucene.Net.Tests.Facet/SlowRAMDirectory.cs +++ b/src/Lucene.Net.Tests.Facet/SlowRAMDirectory.cs @@ -241,7 +241,7 @@ public override long GetFilePointer() public override long Length { get => io.Length; - set => throw new InvalidOperationException("Length is readonly"); + set => throw IllegalStateException.Create("Length is readonly"); // LUCENENET specific: We cannot override get without also overriding set, so we throw if it is set } public override long Checksum => io.Checksum; diff --git a/src/Lucene.Net.Tests.Facet/SortedSet/TestSortedSetDocValuesFacets.cs b/src/Lucene.Net.Tests.Facet/SortedSet/TestSortedSetDocValuesFacets.cs index 1ee9d2df84..6d8bf87b74 100644 --- a/src/Lucene.Net.Tests.Facet/SortedSet/TestSortedSetDocValuesFacets.cs +++ b/src/Lucene.Net.Tests.Facet/SortedSet/TestSortedSetDocValuesFacets.cs @@ -142,7 +142,7 @@ public virtual void TestStaleState() _ = new SortedSetDocValuesFacetCounts(state, c); fail("did not hit expected exception"); } - catch (InvalidOperationException) + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestAddTaxonomy.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestAddTaxonomy.cs index de895d765a..6d58824827 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestAddTaxonomy.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestAddTaxonomy.cs @@ -99,9 +99,9 @@ public override void Run() { tw.AddCategory(new FacetLabel("a", cat)); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } @@ -297,10 +297,10 @@ public override void Run() { destTW.AddCategory(new FacetLabel("a", Convert.ToString(i, CultureInfo.InvariantCulture))); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { // shouldn't happen - if it does, let the test fail on uncaught exception. - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestConcurrentFacetedIndexing.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestConcurrentFacetedIndexing.cs index 9a2f56da8e..8b281f738c 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestConcurrentFacetedIndexing.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestConcurrentFacetedIndexing.cs @@ -212,9 +212,9 @@ public override void Run() } iw.AddDocument(config.Build(tw, 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.Tests.Facet/Taxonomy/Directory/TestDirectoryTaxonomyReader.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestDirectoryTaxonomyReader.cs index 3c38fff963..1a912f8e67 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestDirectoryTaxonomyReader.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestDirectoryTaxonomyReader.cs @@ -120,7 +120,7 @@ public virtual void TestAlreadyClosed() var _ = ltr.Count; fail("An ObjectDisposedException should have been thrown here"); } - catch (ObjectDisposedException) + catch (Exception ace) when (ace.IsAlreadyClosedException()) { // good! } diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestDirectoryTaxonomyWriter.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestDirectoryTaxonomyWriter.cs index c6d6241541..097985cb1b 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestDirectoryTaxonomyWriter.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/Directory/TestDirectoryTaxonomyWriter.cs @@ -148,7 +148,7 @@ public virtual void TestRollback() dtw.AddCategory(new FacetLabel("a")); fail("should not have succeeded to add a category following rollback."); } - catch (ObjectDisposedException) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -181,7 +181,7 @@ public virtual void TestEnsureOpen() dtw.AddCategory(new FacetLabel("a")); fail("should not have succeeded to add a category following close."); } - catch (ObjectDisposedException) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -383,9 +383,9 @@ public override void Run() values[l3] = l3; values[l4] = l4; } - 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.Tests.Facet/Taxonomy/TestCachedOrdinalsReader.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestCachedOrdinalsReader.cs index f23cd738e1..a8e8252c14 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestCachedOrdinalsReader.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestCachedOrdinalsReader.cs @@ -104,9 +104,9 @@ public override void Run() { ordsReader.GetReader(context); } - 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.Tests.Facet/Taxonomy/TestFacetLabel.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestFacetLabel.cs index 59960e0263..898842d7a9 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestFacetLabel.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestFacetLabel.cs @@ -181,7 +181,7 @@ public virtual void TestEmptyNullComponents() Assert.IsNotNull(new FacetLabel(components)); fail("empty or null components should not be allowed: " + Arrays.ToString(components)); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -190,7 +190,7 @@ public virtual void TestEmptyNullComponents() _ = new FacetField("dim", components); fail("empty or null components should not be allowed: " + Arrays.ToString(components)); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -199,7 +199,7 @@ public virtual void TestEmptyNullComponents() _ = new AssociationFacetField(new BytesRef(), "dim", components); fail("empty or null components should not be allowed: " + Arrays.ToString(components)); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -208,7 +208,7 @@ public virtual void TestEmptyNullComponents() _ = new Int32AssociationFacetField(17, "dim", components); fail("empty or null components should not be allowed: " + Arrays.ToString(components)); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -217,7 +217,7 @@ public virtual void TestEmptyNullComponents() _ = new SingleAssociationFacetField(17.0f, "dim", components); fail("empty or null components should not be allowed: " + Arrays.ToString(components)); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -227,7 +227,7 @@ public virtual void TestEmptyNullComponents() _ = new FacetField(null, new string[] { "abc" }); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -236,7 +236,7 @@ public virtual void TestEmptyNullComponents() _ = new FacetField("", new string[] { "abc" }); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -245,7 +245,7 @@ public virtual void TestEmptyNullComponents() _ = new Int32AssociationFacetField(17, null, new string[] { "abc" }); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -254,7 +254,7 @@ public virtual void TestEmptyNullComponents() _ = new Int32AssociationFacetField(17, "", new string[] { "abc" }); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -263,7 +263,7 @@ public virtual void TestEmptyNullComponents() _ = new SingleAssociationFacetField(17.0f, null, new string[] { "abc" }); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -272,7 +272,7 @@ public virtual void TestEmptyNullComponents() _ = new SingleAssociationFacetField(17.0f, "", new string[] { "abc" }); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -281,7 +281,7 @@ public virtual void TestEmptyNullComponents() _ = new AssociationFacetField(new BytesRef(), null, new string[] { "abc" }); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -290,7 +290,7 @@ public virtual void TestEmptyNullComponents() _ = new AssociationFacetField(new BytesRef(), "", new string[] { "abc" }); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -299,7 +299,7 @@ public virtual void TestEmptyNullComponents() _ = new SortedSetDocValuesFacetField(null, "abc"); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -308,7 +308,7 @@ public virtual void TestEmptyNullComponents() _ = new SortedSetDocValuesFacetField("", "abc"); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -317,7 +317,7 @@ public virtual void TestEmptyNullComponents() _ = new SortedSetDocValuesFacetField("dim", null); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -326,7 +326,7 @@ public virtual void TestEmptyNullComponents() _ = new SortedSetDocValuesFacetField("dim", ""); fail("empty or null components should not be allowed"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -352,7 +352,7 @@ public virtual void TestLongPath() Assert.IsNotNull(new FacetLabel("dim", bigComp)); fail("long paths should not be allowed; len=" + bigComp.Length); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/TestSearcherTaxonomyManager.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestSearcherTaxonomyManager.cs index 5fad91adc6..43fa4615cc 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestSearcherTaxonomyManager.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestSearcherTaxonomyManager.cs @@ -110,9 +110,9 @@ public override void Run() mgr.MaybeRefresh(); } } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } if (Verbose) @@ -247,9 +247,9 @@ public override void Run() Console.WriteLine("TEST: reopen done"); } } - catch (Exception ioe) + catch (Exception ioe) when (ioe.IsException()) { - throw new Exception(ioe.Message, ioe); + throw RuntimeException.Create(ioe); } } } @@ -346,7 +346,7 @@ public virtual void TestReplaceTaxonomyNrt() mgr.MaybeRefresh(); fail("should have hit exception"); } - catch (InvalidOperationException) + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyCombined.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyCombined.cs index 2a8bc3eff0..b1c1fb2e33 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyCombined.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyCombined.cs @@ -546,7 +546,7 @@ private void CheckWriterParent(TaxonomyReader tr, ITaxonomyWriter tw) tw.GetParent(-1); fail("getParent for -1 should throw exception"); } - catch (IndexOutOfRangeException) + catch (Exception e) when(e.IsArrayIndexOutOfBoundsException()) { // ok } @@ -555,7 +555,7 @@ private void CheckWriterParent(TaxonomyReader tr, ITaxonomyWriter tw) tw.GetParent(TaxonomyReader.INVALID_ORDINAL); fail("getParent for INVALID_ORDINAL should throw exception"); } - catch (IndexOutOfRangeException) + catch (Exception e) when (e.IsArrayIndexOutOfBoundsException()) { // ok } @@ -564,7 +564,7 @@ private void CheckWriterParent(TaxonomyReader tr, ITaxonomyWriter tw) int parent = tw.GetParent(tr.Count); fail("getParent for getSize() should throw exception, but returned " + parent); } - catch (IndexOutOfRangeException) + catch (Exception e) when (e.IsArrayIndexOutOfBoundsException()) { // ok } @@ -909,7 +909,7 @@ public override void Run() Thread.Sleep(10);// don't starve refresh()'s CPU, which sleeps every 50 bytes for 1 ms } } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { error[0] = e; stop.Value = true; @@ -983,7 +983,7 @@ public virtual void TestSeparateReaderAndWriter() Assert.AreEqual(TaxonomyReader.ROOT_ORDINAL, tr.ParallelTaxonomyArrays.Parents[author]); // ok } - catch (IndexOutOfRangeException) + catch (Exception e) when (e.IsArrayIndexOutOfBoundsException()) { fail("After category addition, commit() and refresh(), getParent for " + author + " should NOT throw exception"); } diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetAssociations.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetAssociations.cs index 87913a10da..5df4b5c987 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetAssociations.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetAssociations.cs @@ -178,7 +178,7 @@ public virtual void TestWrongIndexFieldName() facets.GetSpecificValue("float"); fail("should have hit exc"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -188,7 +188,7 @@ public virtual void TestWrongIndexFieldName() facets.GetTopChildren(10, "float"); fail("should have hit exc"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -216,7 +216,7 @@ public virtual void TestMixedTypesInSameIndexField() writer.AddDocument(config.Build(taxoWriter, doc)); fail("did not hit expected exception"); } - catch (ArgumentException) + catch (Exception exc) when (exc.IsIllegalArgumentException()) { // expected } @@ -245,7 +245,7 @@ public virtual void TestNoHierarchy() writer.AddDocument(config.Build(taxoWriter, doc)); fail("did not hit expected exception"); } - catch (ArgumentException) + catch (Exception exc) when (exc.IsIllegalArgumentException()) { // expected } @@ -274,7 +274,7 @@ public virtual void TestRequireDimCount() writer.AddDocument(config.Build(taxoWriter, doc)); fail("did not hit expected exception"); } - catch (ArgumentException) + catch (Exception exc) when (exc.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts.cs index 8858f1b8cf..fb349041a6 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetCounts.cs @@ -275,7 +275,7 @@ public virtual void TestWrongIndexFieldName() facets.GetSpecificValue("a"); fail("should have hit exc"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -285,7 +285,7 @@ public virtual void TestWrongIndexFieldName() facets.GetTopChildren(10, "a"); fail("should have hit exc"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -372,7 +372,7 @@ public virtual void TestMultiValuedHierarchy() facets.GetSpecificValue("a"); fail("didn't hit expected exception"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -472,7 +472,7 @@ public virtual void TestRequireDimCount() Assert.AreEqual(1, facets.GetSpecificValue("dim")); fail("didn't hit expected exception"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -558,7 +558,7 @@ public virtual void TestDetectHierarchicalField() config.Build(taxoWriter, doc); fail("did not hit expected exception"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -589,7 +589,7 @@ public virtual void TestDetectMultiValuedField() config.Build(taxoWriter, doc); fail("did not hit expected exception"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetSumValueSource.cs b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetSumValueSource.cs index 3e7a0bd90e..e29cbb79c5 100644 --- a/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetSumValueSource.cs +++ b/src/Lucene.Net.Tests.Facet/Taxonomy/TestTaxonomyFacetSumValueSource.cs @@ -255,7 +255,7 @@ public virtual void TestWrongIndexFieldName() facets.GetSpecificValue("a"); fail("should have hit exc"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -265,7 +265,7 @@ public virtual void TestWrongIndexFieldName() facets.GetTopChildren(10, "a"); fail("should have hit exc"); } - catch (ArgumentException) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -411,9 +411,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.Tests.Highlighter/Highlight/HighlighterTest.cs b/src/Lucene.Net.Tests.Highlighter/Highlight/HighlighterTest.cs index b6b666e225..c40b9e3fc6 100644 --- a/src/Lucene.Net.Tests.Highlighter/Highlight/HighlighterTest.cs +++ b/src/Lucene.Net.Tests.Highlighter/Highlight/HighlighterTest.cs @@ -2222,7 +2222,7 @@ public Highlighter GetHighlighter(Query query, String fieldName, IFormatter form } else { - throw new Exception("Unknown highlight mode"); + throw RuntimeException.Create("Unknown highlight mode"); } return new Highlighter(formatter, scorer); @@ -2241,7 +2241,7 @@ internal Highlighter GetHighlighter(WeightedTerm[] weightedTerms, IFormatter for } else { - throw new Exception("Unknown highlight mode"); + throw RuntimeException.Create("Unknown highlight mode"); } } diff --git a/src/Lucene.Net.Tests.Highlighter/Highlight/TokenSourcesTest.cs b/src/Lucene.Net.Tests.Highlighter/Highlight/TokenSourcesTest.cs index 84e97468b4..5510eaeec5 100644 --- a/src/Lucene.Net.Tests.Highlighter/Highlight/TokenSourcesTest.cs +++ b/src/Lucene.Net.Tests.Highlighter/Highlight/TokenSourcesTest.cs @@ -315,9 +315,7 @@ public void TestTermVectorWithoutOffsetsThrowsException() false); fail("TokenSources.getTokenStream should throw IllegalArgumentException if term vector has no offsets"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests.Highlighter/PostingsHighlight/TestPostingsHighlighter.cs b/src/Lucene.Net.Tests.Highlighter/PostingsHighlight/TestPostingsHighlighter.cs index 8228ecc345..070ddfa2a3 100644 --- a/src/Lucene.Net.Tests.Highlighter/PostingsHighlight/TestPostingsHighlighter.cs +++ b/src/Lucene.Net.Tests.Highlighter/PostingsHighlight/TestPostingsHighlighter.cs @@ -431,9 +431,7 @@ public void TestUserFailedToIndexOffsets() highlighter.Highlight("body", query, searcher, topDocs, 2); fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -443,9 +441,7 @@ public void TestUserFailedToIndexOffsets() highlighter.Highlight("title", new TermQuery(new Term("title", "test")), searcher, topDocs, 2); fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests.Highlighter/VectorHighlight/SimpleFragListBuilderTest.cs b/src/Lucene.Net.Tests.Highlighter/VectorHighlight/SimpleFragListBuilderTest.cs index 0d5d312069..787aa8eea7 100644 --- a/src/Lucene.Net.Tests.Highlighter/VectorHighlight/SimpleFragListBuilderTest.cs +++ b/src/Lucene.Net.Tests.Highlighter/VectorHighlight/SimpleFragListBuilderTest.cs @@ -41,9 +41,7 @@ public void TestTooSmallFragSize() sflb.CreateFieldFragList(fpl(new TermQuery(new Term(F, "a")), "b c d"), sflb.minFragCharSize - 1); fail("IllegalArgumentException must be thrown"); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { } } diff --git a/src/Lucene.Net.Tests.Join/TestBlockJoin.cs b/src/Lucene.Net.Tests.Join/TestBlockJoin.cs index 6e0c8227f6..c12ae3f601 100644 --- a/src/Lucene.Net.Tests.Join/TestBlockJoin.cs +++ b/src/Lucene.Net.Tests.Join/TestBlockJoin.cs @@ -1600,7 +1600,15 @@ public void TestChildQueryMatchesParent() ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(new Sort(new SortField("parentID", SortFieldType.STRING)), 10, true, true); - Assert.Throws(() => NewSearcher(r).Search(parentQuery, c)); + try + { + NewSearcher(r).Search(parentQuery, c); + fail("should have hit exception"); + } + catch (Exception ise) when (ise.IsIllegalStateException()) + { + // expected + } r.Dispose(); d.Dispose(); diff --git a/src/Lucene.Net.Tests.Join/TestBlockJoinValidation.cs b/src/Lucene.Net.Tests.Join/TestBlockJoinValidation.cs index f38f87f91f..9e97e12fcf 100644 --- a/src/Lucene.Net.Tests.Join/TestBlockJoinValidation.cs +++ b/src/Lucene.Net.Tests.Join/TestBlockJoinValidation.cs @@ -67,9 +67,16 @@ public void TestNextDocValidationForToParentBjq() Query parentQueryWithRandomChild = CreateChildrenQueryWithOneParent(GetRandomChildNumber(0)); var blockJoinQuery = new ToParentBlockJoinQuery(parentQueryWithRandomChild, parentsFilter, ScoreMode.None); - var ex = Assert.Throws(() => indexSearcher.Search(blockJoinQuery, 1)); - StringAssert.Contains("child query must only match non-parent docs", ex.Message); - + // LUCENENET: Refactored to allow us to use our IsIllegalStateException() extension method + try + { + indexSearcher.Search(blockJoinQuery, 1); + fail(); + } + catch (Exception ise) when (ise.IsIllegalStateException()) + { + assertTrue(ise.Message.Contains("child query must only match non-parent docs")); + } } [Test] @@ -87,8 +94,16 @@ public void TestAdvanceValidationForToParentBjq() conjunctionQuery.Add(new BooleanClause(childQuery, Occur.MUST)); conjunctionQuery.Add(new BooleanClause(blockJoinQuery, Occur.MUST)); - var ex = Assert.Throws(() => indexSearcher.Search(conjunctionQuery, 1)); - StringAssert.Contains("child query must only match non-parent docs", ex.Message); + // LUCENENET: Refactored to allow us to use our IsIllegalStateException() extension method + try + { + indexSearcher.Search(conjunctionQuery, 1); + fail(); + } + catch (Exception ise) when (ise.IsIllegalStateException()) + { + assertTrue(ise.Message.Contains("child query must only match non-parent docs")); + } } [Test] @@ -97,8 +112,16 @@ public void TestNextDocValidationForToChildBjq() Query parentQueryWithRandomChild = CreateParentsQueryWithOneChild(GetRandomChildNumber(0)); var blockJoinQuery = new ToChildBlockJoinQuery(parentQueryWithRandomChild, parentsFilter, false); - var ex = Assert.Throws(() => indexSearcher.Search(blockJoinQuery, 1)); - StringAssert.Contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE, ex.Message); + // LUCENENET: Refactored to allow us to use our IsIllegalStateException() extension method + try + { + indexSearcher.Search(blockJoinQuery, 1); + fail(); + } + catch (Exception ise) when (ise.IsIllegalStateException()) + { + assertTrue(ise.Message.Contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE)); + } } [Test] @@ -116,8 +139,16 @@ public void TestAdvanceValidationForToChildBjq() conjunctionQuery.Add(new BooleanClause(childQuery, Occur.MUST)); conjunctionQuery.Add(new BooleanClause(blockJoinQuery, Occur.MUST)); - var ex = Assert.Throws(() => indexSearcher.Search(conjunctionQuery, 1)); - StringAssert.Contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE, ex.Message); + // LUCENENET: Refactored to allow us to use our IsIllegalStateException() extension method + try + { + indexSearcher.Search(conjunctionQuery, 1); + fail(); + } + catch (Exception ise) when (ise.IsIllegalStateException()) + { + assertTrue(ise.Message.Contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE)); + } } [TearDown] diff --git a/src/Lucene.Net.Tests.Misc/Document/TestLazyDocument.cs b/src/Lucene.Net.Tests.Misc/Document/TestLazyDocument.cs index 64ea0d9510..f6bdfcf64b 100644 --- a/src/Lucene.Net.Tests.Misc/Document/TestLazyDocument.cs +++ b/src/Lucene.Net.Tests.Misc/Document/TestLazyDocument.cs @@ -1,4 +1,4 @@ -/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -44,7 +44,7 @@ public class TestLazyDocument : LuceneTestCase public Directory dir = NewDirectory(); [OneTimeTearDown] - public override void AfterClass() // LUCENENET specific - changed from CreateIndex() to ensure calling order vs base class + public override void AfterClass() // LUCENENET specific - changed from RemoveIndex() to ensure calling order vs base class { if (null != dir) { @@ -53,7 +53,7 @@ public override void AfterClass() // LUCENENET specific - changed from CreateInd dir.Dispose(); dir = null; } - catch (Exception /*e*/) { /* NOOP */ } + catch (Exception e) when (e.IsException()) { /* NOOP */ } } base.AfterClass(); diff --git a/src/Lucene.Net.Tests.Misc/Index/Sorter/SortingAtomicReaderTest.cs b/src/Lucene.Net.Tests.Misc/Index/Sorter/SortingAtomicReaderTest.cs index 8a8f80abd4..9a734de61e 100644 --- a/src/Lucene.Net.Tests.Misc/Index/Sorter/SortingAtomicReaderTest.cs +++ b/src/Lucene.Net.Tests.Misc/Index/Sorter/SortingAtomicReaderTest.cs @@ -76,7 +76,7 @@ public void TestBadSort() SortingAtomicReader.Wrap(reader, Sort.RELEVANCE); fail("Didn't get expected exception"); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { assertEquals("Cannot sort an index with a Sort that refers to the relevance score", e.Message); } diff --git a/src/Lucene.Net.Tests.Misc/Index/Sorter/TestSortingMergePolicy.cs b/src/Lucene.Net.Tests.Misc/Index/Sorter/TestSortingMergePolicy.cs index 3bf4a61f4a..5806efb5cb 100644 --- a/src/Lucene.Net.Tests.Misc/Index/Sorter/TestSortingMergePolicy.cs +++ b/src/Lucene.Net.Tests.Misc/Index/Sorter/TestSortingMergePolicy.cs @@ -179,7 +179,7 @@ public void TestBadSort() new SortingMergePolicy(NewMergePolicy(), Sort.RELEVANCE); fail("Didn't get expected exception"); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { assertEquals("Cannot sort an index with a Sort that refers to the relevance score", e.Message); } diff --git a/src/Lucene.Net.Tests.Queries/CommonTermsQueryTest.cs b/src/Lucene.Net.Tests.Queries/CommonTermsQueryTest.cs index dbf4a85278..996763b86a 100644 --- a/src/Lucene.Net.Tests.Queries/CommonTermsQueryTest.cs +++ b/src/Lucene.Net.Tests.Queries/CommonTermsQueryTest.cs @@ -175,9 +175,7 @@ public void TestNullTerm() query.Add(null); Assert.Fail(@"null values are not supported"); } -#pragma warning disable 168 - catch (ArgumentException ex) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { } } @@ -345,9 +343,7 @@ public void TestIllegalOccur() new CommonTermsQuery(Occur.MUST_NOT, RandomOccur(random), Random.NextSingle()); Assert.Fail(@"MUST_NOT is not supproted"); } -#pragma warning disable 168 - catch (ArgumentException ex) -#pragma warning restore 168 + catch (Exception ex) when (ex.IsIllegalArgumentException()) { } @@ -356,9 +352,7 @@ public void TestIllegalOccur() new CommonTermsQuery(RandomOccur(random), Occur.MUST_NOT, Random.NextSingle()); Assert.Fail(@"MUST_NOT is not supproted"); } -#pragma warning disable 168 - catch (ArgumentException ex) -#pragma warning restore 168 + catch (Exception ex) when (ex.IsIllegalArgumentException()) { } } diff --git a/src/Lucene.Net.Tests.Queries/Function/TestDocValuesFieldSources.cs b/src/Lucene.Net.Tests.Queries/Function/TestDocValuesFieldSources.cs index 8c4e6c3da1..1e33cc177c 100644 --- a/src/Lucene.Net.Tests.Queries/Function/TestDocValuesFieldSources.cs +++ b/src/Lucene.Net.Tests.Queries/Function/TestDocValuesFieldSources.cs @@ -54,7 +54,7 @@ private void DoTest(DocValuesType type) f = new NumericDocValuesField("dv", 0); break; default: - throw new InvalidOperationException(); + throw AssertionError.Create(); } Document document = new Document(); document.Add(id); @@ -105,7 +105,7 @@ private void DoTest(DocValuesType type) vs = new Int64FieldSource("dv"); break; default: - throw new InvalidOperationException(); + throw AssertionError.Create(); } FunctionValues values = vs.GetValues(null, leave); BytesRef bytes = new BytesRef(); @@ -123,7 +123,7 @@ private void DoTest(DocValuesType type) } else { - throw new InvalidOperationException(); + throw AssertionError.Create(); } object expected = vals[ids.Int32Val(i)]; diff --git a/src/Lucene.Net.Tests.Queries/TermFilterTest.cs b/src/Lucene.Net.Tests.Queries/TermFilterTest.cs index d8cd554976..2c8d670b3f 100644 --- a/src/Lucene.Net.Tests.Queries/TermFilterTest.cs +++ b/src/Lucene.Net.Tests.Queries/TermFilterTest.cs @@ -175,9 +175,7 @@ public void TestNoTerms() new TermFilter(null); Assert.Fail(@"must fail - no term!"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { } @@ -186,9 +184,7 @@ public void TestNoTerms() new TermFilter(new Term(null)); Assert.Fail(@"must fail - no field!"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { } } diff --git a/src/Lucene.Net.Tests.QueryParser/Analyzing/TestAnalyzingQueryParser.cs b/src/Lucene.Net.Tests.QueryParser/Analyzing/TestAnalyzingQueryParser.cs index 0caca62fd7..8174b61cc3 100644 --- a/src/Lucene.Net.Tests.QueryParser/Analyzing/TestAnalyzingQueryParser.cs +++ b/src/Lucene.Net.Tests.QueryParser/Analyzing/TestAnalyzingQueryParser.cs @@ -1,17 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Lucene.Net.Analysis; +using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Documents; using Lucene.Net.Index; -using Lucene.Net.QueryParsers.Classic; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Util; using NUnit.Framework; +using System; +using System.Collections.Generic; namespace Lucene.Net.QueryParsers.Analyzing { @@ -104,7 +100,7 @@ public virtual void TestSingleChunkExceptions() { string q = ParseWithAnalyzingQueryParser(termStr, stopsAnalyzer, true); } - catch (ParseException e) + catch (Lucene.Net.QueryParsers.Classic.ParseException e) { if (e.Message.Contains("returned nothing")) { @@ -119,7 +115,7 @@ public virtual void TestSingleChunkExceptions() { qp.AnalyzeSingleChunk(FIELD, "", "not a single chunk"); } - catch (ParseException e) + catch (Lucene.Net.QueryParsers.Classic.ParseException e) { if (e.Message.Contains("multiple terms")) { @@ -138,7 +134,7 @@ public virtual void TestWildcardAlone() { Query q = GetAnalyzedQuery("*", a, false); } - catch (ParseException /*e*/) + catch (Lucene.Net.QueryParsers.Classic.ParseException /*e*/) { pex = true; } @@ -150,7 +146,7 @@ public virtual void TestWildcardAlone() String qString = ParseWithAnalyzingQueryParser("*", a, true); assertEquals("Every word", "*", qString); } - catch (ParseException /*e*/) + catch (Lucene.Net.QueryParsers.Classic.ParseException /*e*/) { pex = true; } @@ -182,7 +178,7 @@ public virtual void TestWildCardQueryNoLeadingAllowed() string q = ParseWithAnalyzingQueryParser(wildcardInput[0], a, false); } - catch (ParseException /*e*/) + catch (Lucene.Net.QueryParsers.Classic.ParseException /*e*/) { ex = true; } diff --git a/src/Lucene.Net.Tests.QueryParser/Classic/TestMultiFieldQueryParser.cs b/src/Lucene.Net.Tests.QueryParser/Classic/TestMultiFieldQueryParser.cs index 8132c8bafd..4a90534562 100644 --- a/src/Lucene.Net.Tests.QueryParser/Classic/TestMultiFieldQueryParser.cs +++ b/src/Lucene.Net.Tests.QueryParser/Classic/TestMultiFieldQueryParser.cs @@ -182,7 +182,7 @@ public virtual void TestStaticMethod1() q = MultiFieldQueryParser.Parse(TEST_VERSION_CURRENT, queries5, fields, new MockAnalyzer(Random)); fail(); } - catch (ArgumentException /*e*/) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } @@ -216,7 +216,7 @@ public virtual void TestStaticMethod2() q = MultiFieldQueryParser.Parse(TEST_VERSION_CURRENT, "blah", fields, flags2, new MockAnalyzer(Random)); fail(); } - catch (ArgumentException /*e*/) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } @@ -241,7 +241,7 @@ public virtual void TestStaticMethod2Old() q = MultiFieldQueryParser.Parse(TEST_VERSION_CURRENT, "blah", fields, flags2, new MockAnalyzer(Random)); fail(); } - catch (ArgumentException /*e*/) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } @@ -263,7 +263,7 @@ public virtual void TestStaticMethod3() q = MultiFieldQueryParser.Parse(TEST_VERSION_CURRENT, queries, fields, flags2, new MockAnalyzer(Random)); fail(); } - catch (ArgumentException /*e*/) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } @@ -284,7 +284,7 @@ public virtual void TestStaticMethod3Old() q = MultiFieldQueryParser.Parse(TEST_VERSION_CURRENT, queries, fields, flags2, new MockAnalyzer(Random)); fail(); } - catch (ArgumentException /*e*/) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } diff --git a/src/Lucene.Net.Tests.QueryParser/Classic/TestQueryParser.cs b/src/Lucene.Net.Tests.QueryParser/Classic/TestQueryParser.cs index bf3e2db117..58a733745e 100644 --- a/src/Lucene.Net.Tests.QueryParser/Classic/TestQueryParser.cs +++ b/src/Lucene.Net.Tests.QueryParser/Classic/TestQueryParser.cs @@ -181,7 +181,7 @@ internal override Query HandleBareFuzzy(string qfield, Token fuzzySlop, string t { fms = float.Parse(fuzzySlop.Image.Substring(1, fuzzySlop.Image.Length - 2), CultureInfo.InvariantCulture); } - catch (Exception /*ignored*/) { } + catch (Exception /*ignored*/) { } // LUCENENET: No need to call the IsException() extension method here because we are dealing only with a .NET platform method float value = float.Parse(termImage, CultureInfo.InvariantCulture); return GetRangeQuery(qfield, (value - fms / 2.0f).ToString(CultureInfo.InvariantCulture), (value + fms / 2.0f).ToString(CultureInfo.InvariantCulture), true, true); } @@ -276,7 +276,7 @@ public virtual void TestCustomQueryParserWildcard() MockTokenizer.WHITESPACE, false)).Parse("a?t"); fail("Wildcard queries should not be allowed"); } - catch (ParseException /*expected*/) + catch (Lucene.Net.QueryParsers.Classic.ParseException /*expected*/) // LUCENENET: Classic QueryParser has its own ParseException that is different than the one in Support { // expected exception } @@ -291,7 +291,7 @@ public virtual void TestCustomQueryParserFuzzy() MockTokenizer.WHITESPACE, false)).Parse("xunit~"); fail("Fuzzy queries should not be allowed"); } - catch (ParseException /*expected*/) + catch (Lucene.Net.QueryParsers.Classic.ParseException /*expected*/) // LUCENENET: Classic QueryParser has its own ParseException that is different than the one in Support { // expected exception } diff --git a/src/Lucene.Net.Tests.QueryParser/ComplexPhrase/TestComplexPhraseQuery.cs b/src/Lucene.Net.Tests.QueryParser/ComplexPhrase/TestComplexPhraseQuery.cs index c49e1538dd..05fe92cc7c 100644 --- a/src/Lucene.Net.Tests.QueryParser/ComplexPhrase/TestComplexPhraseQuery.cs +++ b/src/Lucene.Net.Tests.QueryParser/ComplexPhrase/TestComplexPhraseQuery.cs @@ -92,7 +92,7 @@ private void CheckBadQuery(String qString) { qp.Parse(qString); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { expected = e; } diff --git a/src/Lucene.Net.Tests.QueryParser/Ext/TestExtendableQueryParser.cs b/src/Lucene.Net.Tests.QueryParser/Ext/TestExtendableQueryParser.cs index af3b21a7b8..9d243201e6 100644 --- a/src/Lucene.Net.Tests.QueryParser/Ext/TestExtendableQueryParser.cs +++ b/src/Lucene.Net.Tests.QueryParser/Ext/TestExtendableQueryParser.cs @@ -59,7 +59,7 @@ public virtual void TestUnescapedExtDelimiter() parser.Parse("aField:testExt:\"foo \\& bar\""); fail("extension field delimiter is not escaped"); } - catch (ParseException /*e*/) + catch (Lucene.Net.QueryParsers.Classic.ParseException /*e*/) { } } diff --git a/src/Lucene.Net.Tests.QueryParser/Ext/TestExtensions.cs b/src/Lucene.Net.Tests.QueryParser/Ext/TestExtensions.cs index c8a0d6c50f..91de1ea154 100644 --- a/src/Lucene.Net.Tests.QueryParser/Ext/TestExtensions.cs +++ b/src/Lucene.Net.Tests.QueryParser/Ext/TestExtensions.cs @@ -87,7 +87,7 @@ public virtual void TestEscapeExtension() ext.EscapeExtensionField(null); fail("should throw NPE - escape string is null"); } - catch (NullReferenceException /*e*/) + catch (ArgumentNullException /*e*/) // LUCENENET specific - Added guard clause to throw ArgumentNullException instead of letting NullReferenceException happen. { // } diff --git a/src/Lucene.Net.Tests.QueryParser/Flexible/Precedence/TestPrecedenceQueryParser.cs b/src/Lucene.Net.Tests.QueryParser/Flexible/Precedence/TestPrecedenceQueryParser.cs index 7b8dcf91f0..e1adb1fd15 100644 --- a/src/Lucene.Net.Tests.QueryParser/Flexible/Precedence/TestPrecedenceQueryParser.cs +++ b/src/Lucene.Net.Tests.QueryParser/Flexible/Precedence/TestPrecedenceQueryParser.cs @@ -333,7 +333,7 @@ public void TestWildcard() fail(); } #pragma warning disable 168 - catch (ParseException pe) + catch (Lucene.Net.QueryParsers.Flexible.Standard.Parser.ParseException pe) #pragma warning restore 168 { // expected exception diff --git a/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestMultiFieldQPHelper.cs b/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestMultiFieldQPHelper.cs index eeee49b301..fd2573a683 100644 --- a/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestMultiFieldQPHelper.cs +++ b/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestMultiFieldQPHelper.cs @@ -203,9 +203,7 @@ public void TestStaticMethod1() q = QueryParserUtil.Parse(queries5, fields, new MockAnalyzer(Random)); fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } @@ -245,9 +243,7 @@ public void TestStaticMethod2() q = QueryParserUtil.Parse("blah", fields, flags2, new MockAnalyzer(Random)); fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } @@ -280,9 +276,7 @@ public void TestStaticMethod2Old() q = QueryParserUtil.Parse("blah", fields, flags2, new MockAnalyzer(Random)); fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } @@ -310,9 +304,7 @@ public void TestStaticMethod3() .Parse(queries, fields, flags2, new MockAnalyzer(Random)); fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } @@ -340,9 +332,7 @@ public void TestStaticMethod3Old() .Parse(queries, fields, flags2, new MockAnalyzer(Random)); fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception, array length differs } diff --git a/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestStandardQP.cs b/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestStandardQP.cs index a8d156b932..137a2e9f3a 100644 --- a/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestStandardQP.cs +++ b/src/Lucene.Net.Tests.QueryParser/Flexible/Standard/TestStandardQP.cs @@ -97,14 +97,14 @@ public override void SetDefaultOperatorAND(ICommonQueryParserConfiguration cqpC) public override void SetAnalyzeRangeTerms(ICommonQueryParserConfiguration cqpC, bool value) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override void SetAutoGeneratePhraseQueries(ICommonQueryParserConfiguration cqpC, bool value) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } @@ -175,9 +175,7 @@ public override void TestCollatedRange() SetAnalyzeRangeTerms(GetParser(null), true); base.TestCollatedRange(); } -#pragma warning disable 168 - catch (NotSupportedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected } @@ -191,9 +189,7 @@ public override void TestAutoGeneratePhraseQueriesOn() SetAutoGeneratePhraseQueries(GetParser(null), true); base.TestAutoGeneratePhraseQueriesOn(); } -#pragma warning disable 168 - catch (NotSupportedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsUnsupportedOperationException()) { // expected } diff --git a/src/Lucene.Net.Tests.QueryParser/Surround/Query/ExceptionQueryTst.cs b/src/Lucene.Net.Tests.QueryParser/Surround/Query/ExceptionQueryTst.cs index 930999581b..91ba9522b9 100644 --- a/src/Lucene.Net.Tests.QueryParser/Surround/Query/ExceptionQueryTst.cs +++ b/src/Lucene.Net.Tests.QueryParser/Surround/Query/ExceptionQueryTst.cs @@ -45,7 +45,7 @@ public void DoTest(StringBuilder failQueries) Console.WriteLine("Query: " + queryText + "\nParsed as: " + lq.ToString()); } } - catch (ParseException e) + catch (Lucene.Net.QueryParsers.Surround.Parser.ParseException e) { if (verbose) { diff --git a/src/Lucene.Net.Tests.QueryParser/Util/QueryParserTestBase.cs b/src/Lucene.Net.Tests.QueryParser/Util/QueryParserTestBase.cs index af1fa509bc..cd7c301418 100644 --- a/src/Lucene.Net.Tests.QueryParser/Util/QueryParserTestBase.cs +++ b/src/Lucene.Net.Tests.QueryParser/Util/QueryParserTestBase.cs @@ -1,4 +1,4 @@ -/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -975,7 +975,7 @@ public void AssertParseException(string queryString) { GetQuery(queryString); } - catch (Exception expected) + catch (Exception expected) when (expected.IsException()) { if (IsQueryParserException(expected)) { @@ -991,7 +991,7 @@ public void AssertParseException(string queryString, Analyzer a) { GetQuery(queryString, a); } - catch (Exception expected) + catch (Exception expected) when (expected.IsException()) { if (IsQueryParserException(expected)) { diff --git a/src/Lucene.Net.Tests.Replicator/IndexAndTaxonomyReplicationClientTest.cs b/src/Lucene.Net.Tests.Replicator/IndexAndTaxonomyReplicationClientTest.cs index cd8e9f245d..6a43d60bc0 100644 --- a/src/Lucene.Net.Tests.Replicator/IndexAndTaxonomyReplicationClientTest.cs +++ b/src/Lucene.Net.Tests.Replicator/IndexAndTaxonomyReplicationClientTest.cs @@ -14,6 +14,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Runtime.ExceptionServices; using System.Threading; using Console = Lucene.Net.Util.SystemConsole; using Directory = Lucene.Net.Store.Directory; @@ -138,6 +139,7 @@ private void AssertHandlerRevision(int expectedId, Directory dir) while (client.IsUpdateThreadAlive) { Thread.Sleep(100); + // LUCENENET NOTE: No need to catch and rethrow same excepton type ThreadInterruptedException. try { @@ -479,7 +481,7 @@ protected override void HandleUpdateException(Exception exception) } else { - throw exception; + ExceptionDispatchInfo.Capture(exception).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } } } diff --git a/src/Lucene.Net.Tests.Replicator/IndexAndTaxonomyRevisionTest.cs b/src/Lucene.Net.Tests.Replicator/IndexAndTaxonomyRevisionTest.cs index 20d978cc36..9507232d15 100644 --- a/src/Lucene.Net.Tests.Replicator/IndexAndTaxonomyRevisionTest.cs +++ b/src/Lucene.Net.Tests.Replicator/IndexAndTaxonomyRevisionTest.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Facet; using Lucene.Net.Facet.Taxonomy; using Lucene.Net.Index; @@ -54,7 +54,7 @@ public void TestNoCommit() assertNotNull(new IndexAndTaxonomyRevision(indexWriter, taxoWriter)); fail("should have failed when there are no commits to snapshot"); } - catch (InvalidOperationException) + catch (Exception e) when (e.IsIllegalStateException()) { // expected } diff --git a/src/Lucene.Net.Tests.Replicator/IndexReplicationClientTest.cs b/src/Lucene.Net.Tests.Replicator/IndexReplicationClientTest.cs index 3a37774e6b..28450cf770 100644 --- a/src/Lucene.Net.Tests.Replicator/IndexReplicationClientTest.cs +++ b/src/Lucene.Net.Tests.Replicator/IndexReplicationClientTest.cs @@ -10,6 +10,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Runtime.ExceptionServices; using System.Threading; using Console = Lucene.Net.Util.SystemConsole; using Directory = Lucene.Net.Store.Directory; @@ -100,6 +101,8 @@ private void AssertHandlerRevision(int expectedId, Directory dir) { // give client a chance to update Thread.Sleep(100); + // LUCENENET NOTE: No need to catch and rethrow same excepton type ThreadInterruptedException. + try { DirectoryReader reader = DirectoryReader.Open(dir); @@ -385,7 +388,7 @@ protected override void HandleUpdateException(Exception exception) } else { - throw exception; + ExceptionDispatchInfo.Capture(exception).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } } } diff --git a/src/Lucene.Net.Tests.Replicator/IndexRevisionTest.cs b/src/Lucene.Net.Tests.Replicator/IndexRevisionTest.cs index a67257fa5d..a43a51a364 100644 --- a/src/Lucene.Net.Tests.Replicator/IndexRevisionTest.cs +++ b/src/Lucene.Net.Tests.Replicator/IndexRevisionTest.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Util; @@ -41,7 +41,7 @@ public void TestNoSnapshotDeletionPolicy() assertNotNull(new IndexRevision(writer)); fail("should have failed when IndexDeletionPolicy is not Snapshot"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -63,7 +63,7 @@ public void TestNoCommit() assertNotNull(new IndexRevision(writer)); fail("should have failed when there are no commits to snapshot"); } - catch (InvalidOperationException) + catch (Exception e) when (e.IsIllegalStateException()) { // expected } diff --git a/src/Lucene.Net.Tests.Replicator/LocalReplicatorTest.cs b/src/Lucene.Net.Tests.Replicator/LocalReplicatorTest.cs index ad04a482af..4ec74504e4 100644 --- a/src/Lucene.Net.Tests.Replicator/LocalReplicatorTest.cs +++ b/src/Lucene.Net.Tests.Replicator/LocalReplicatorTest.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Util; using NUnit.Framework; @@ -83,7 +83,7 @@ public void TestObtainFileAlreadyClosed() replicator.ObtainFile(res.Id, entry.Key, entry.Value.First().FileName); fail("should have failed on AlreadyClosedException"); } - catch (ObjectDisposedException) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -98,7 +98,7 @@ public void TestPublishAlreadyClosed() replicator.Publish(CreateRevision(2)); fail("should have failed on AlreadyClosedException"); } - catch (ObjectDisposedException) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -113,7 +113,7 @@ public void TestUpdateAlreadyClosed() replicator.CheckForUpdate(null); fail("should have failed on AlreadyClosedException"); } - catch (ObjectDisposedException) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -150,7 +150,7 @@ public void TestPublishOlderRev() replicator.Publish(old); fail("should have failed to publish an older revision"); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -167,15 +167,7 @@ public void TestObtainMissingFile() replicator.ObtainFile(res.Id, res.SourceFiles.Keys.First(), "madeUpFile"); fail("should have failed obtaining an unrecognized file"); } -#pragma warning disable 168 - catch (FileNotFoundException e) -#pragma warning restore 168 - { - // expected - } -#pragma warning disable 168 - catch (DirectoryNotFoundException e) // LUCENENET specific: In Java, a FileNotFound exception is thrown when there is no directory, so we need to cover this case as well -#pragma warning restore 168 + catch (Exception e) when (e.IsNoSuchFileExceptionOrFileNotFoundException()) { // expected } diff --git a/src/Lucene.Net.Tests.Sandbox/Queries/TestSlowFuzzyQuery.cs b/src/Lucene.Net.Tests.Sandbox/Queries/TestSlowFuzzyQuery.cs index a0b3d85996..087c9d5cfd 100644 --- a/src/Lucene.Net.Tests.Sandbox/Queries/TestSlowFuzzyQuery.cs +++ b/src/Lucene.Net.Tests.Sandbox/Queries/TestSlowFuzzyQuery.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Store; @@ -308,9 +308,7 @@ public void TestFuzzinessLong() query = new SlowFuzzyQuery(new Term("field", "student"), 1.1f); fail("Expected IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expecting exception } @@ -319,9 +317,7 @@ public void TestFuzzinessLong() query = new SlowFuzzyQuery(new Term("field", "student"), -0.1f); fail("Expected IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // expecting exception } diff --git a/src/Lucene.Net.Tests.Spatial/Prefix/NtsPolygonTest.cs b/src/Lucene.Net.Tests.Spatial/Prefix/NtsPolygonTest.cs index 47a514a968..63c39c0ee1 100644 --- a/src/Lucene.Net.Tests.Spatial/Prefix/NtsPolygonTest.cs +++ b/src/Lucene.Net.Tests.Spatial/Prefix/NtsPolygonTest.cs @@ -42,7 +42,7 @@ public NtsPolygonTest() typeof(Spatial4n.Core.Context.Nts.NtsSpatialContextFactory).AssemblyQualifiedName); ctx = SpatialContextFactory.MakeSpatialContext(args /*, getClass().getClassLoader()*/); } - catch (TypeLoadException e) //LUCENENET TODO: Does this match NoClassDefFoundError ?? + catch (Exception e) when (e.IsNoClassDefFoundError()) { AssumeTrue("This test requires Spatial4n.Core.NTS: " + e, false); } diff --git a/src/Lucene.Net.Tests.Spatial/Query/SpatialArgsParserTest.cs b/src/Lucene.Net.Tests.Spatial/Query/SpatialArgsParserTest.cs index aa96302fab..478fffbd97 100644 --- a/src/Lucene.Net.Tests.Spatial/Query/SpatialArgsParserTest.cs +++ b/src/Lucene.Net.Tests.Spatial/Query/SpatialArgsParserTest.cs @@ -52,10 +52,9 @@ public virtual void TestArgsParser() parser.Parse(SpatialOperation.IsDisjointTo + "[ ]", ctx); fail("spatial operations need args"); } -#pragma warning disable 168 - catch (Exception ex) -#pragma warning restore 168 - {//expected + catch (Exception ex) when (ex.IsException()) + { + //expected } try @@ -63,10 +62,9 @@ public virtual void TestArgsParser() parser.Parse("XXXX(Envelope(-10, 10, 20, -20))", ctx); fail("unknown operation!"); } -#pragma warning disable 168 - catch (Exception ex) -#pragma warning restore 168 - {//expected + catch (Exception ex) when (ex.IsException()) + { + //expected } } } diff --git a/src/Lucene.Net.Tests.Spatial/QueryEqualsHashCodeTest.cs b/src/Lucene.Net.Tests.Spatial/QueryEqualsHashCodeTest.cs index 3b27e83972..d0c667c75c 100644 --- a/src/Lucene.Net.Tests.Spatial/QueryEqualsHashCodeTest.cs +++ b/src/Lucene.Net.Tests.Spatial/QueryEqualsHashCodeTest.cs @@ -113,9 +113,7 @@ private void TestEqualsHashcode(SpatialArgs args1, SpatialArgs args2, ObjGenerat { first = generator.gen(args1); } -#pragma warning disable 168 - catch (NotSupportedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsUnsupportedOperationException()) { return; } diff --git a/src/Lucene.Net.Tests.Spatial/SpatialTestCase.cs b/src/Lucene.Net.Tests.Spatial/SpatialTestCase.cs index eb6479115b..688c0c8dd5 100644 --- a/src/Lucene.Net.Tests.Spatial/SpatialTestCase.cs +++ b/src/Lucene.Net.Tests.Spatial/SpatialTestCase.cs @@ -122,9 +122,9 @@ protected virtual SearchResults executeQuery(Query query, int numDocs) } return new SearchResults(topDocs.TotalHits, results); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception("IOException thrown while executing query", ioe); + throw RuntimeException.Create("IOException thrown while executing query", ioe); } } diff --git a/src/Lucene.Net.Tests.Spatial/SpatialTestData.cs b/src/Lucene.Net.Tests.Spatial/SpatialTestData.cs index ca56899304..3d0f9e057b 100644 --- a/src/Lucene.Net.Tests.Spatial/SpatialTestData.cs +++ b/src/Lucene.Net.Tests.Spatial/SpatialTestData.cs @@ -1,6 +1,5 @@ using J2N.Text; using Spatial4n.Core.Context; -using Spatial4n.Core.Exceptions; using Spatial4n.Core.Shapes; using System; using System.Collections.Generic; @@ -55,16 +54,16 @@ public static IEnumerator GetTestData(Stream @in, SpatialContex SpatialTestData data = new SpatialTestData(); String[] vals = line.Split('\t').TrimEnd(); if (vals.Length != 3) - throw new Exception("bad format; expecting 3 tab-separated values for line: " + line); + throw RuntimeException.Create("bad format; expecting 3 tab-separated values for line: " + line); data.id = vals[0]; data.name = vals[1]; try { data.shape = ctx.ReadShapeFromWkt(vals[2]); } - catch (ParseException e) + catch (Spatial4n.Core.Exceptions.ParseException e) // LUCENENET: Spatial4n has its own ParseException that is different than the one in Support { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } results.Add(data); } diff --git a/src/Lucene.Net.Tests.Spatial/SpatialTestQuery.cs b/src/Lucene.Net.Tests.Spatial/SpatialTestQuery.cs index 0908e5d420..7494aa7040 100644 --- a/src/Lucene.Net.Tests.Spatial/SpatialTestQuery.cs +++ b/src/Lucene.Net.Tests.Spatial/SpatialTestQuery.cs @@ -81,7 +81,7 @@ public static IEnumerator GetTestQueries( } catch (Exception ex) { - throw new Exception("invalid query line: " + test.line, ex); + throw RuntimeException.Create("invalid query line: " + test.line, ex); } } } diff --git a/src/Lucene.Net.Tests.Suggest/Spell/TestSpellChecker.cs b/src/Lucene.Net.Tests.Suggest/Spell/TestSpellChecker.cs index 3797b6e99f..f74823c777 100644 --- a/src/Lucene.Net.Tests.Suggest/Spell/TestSpellChecker.cs +++ b/src/Lucene.Net.Tests.Suggest/Spell/TestSpellChecker.cs @@ -397,7 +397,7 @@ public void TestClose() // spellChecker.Dispose(); // fail("spellchecker was already closed"); //} - //catch (ObjectDisposedException e) + //catch (Exception e) when (e.IsAlreadyClosedException()) //{ // // expected //} @@ -406,7 +406,7 @@ public void TestClose() CheckCommonSuggestions(r); fail("spellchecker was already closed"); } - catch (ObjectDisposedException /*e*/) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -416,7 +416,7 @@ public void TestClose() spellChecker.ClearIndex(); fail("spellchecker was already closed"); } - catch (ObjectDisposedException /*e*/) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -426,7 +426,7 @@ public void TestClose() spellChecker.IndexDictionary(new LuceneDictionary(r, field), NewIndexWriterConfig(TEST_VERSION_CURRENT, null), false); fail("spellchecker was already closed"); } - catch (ObjectDisposedException /*e*/) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -436,7 +436,7 @@ public void TestClose() spellChecker.SetSpellIndex(spellindex); fail("spellchecker was already closed"); } - catch (ObjectDisposedException /*e*/) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -574,11 +574,11 @@ public override void Run() Thread.Sleep(10);// don't starve refresh()'s CPU, which sleeps every 50 bytes for 1 ms } - catch (ObjectDisposedException /*e*/) + catch (Exception e) when (e.IsAlreadyClosedException()) { return; } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { e.printStackTrace(); error = e; diff --git a/src/Lucene.Net.Tests.Suggest/Spell/TestWordBreakSpellChecker.cs b/src/Lucene.Net.Tests.Suggest/Spell/TestWordBreakSpellChecker.cs index f286e4dba2..b8b27bfb50 100644 --- a/src/Lucene.Net.Tests.Suggest/Spell/TestWordBreakSpellChecker.cs +++ b/src/Lucene.Net.Tests.Suggest/Spell/TestWordBreakSpellChecker.cs @@ -380,7 +380,7 @@ public void TestRandom() } } - //catch (Exception e) // LUCENENET: Senseless to catch and rethrow here + //catch (Exception e) when (e.IsException()) // LUCENENET: Senseless to catch and rethrow here //{ // throw e; //} @@ -390,17 +390,17 @@ public void TestRandom() { ir.Dispose(); } - catch (Exception /*e1*/) { } + catch (Exception e1) when (e1.IsException()) { } try { writer.Dispose(); } - catch (Exception /*e1*/) { } + catch (Exception e1) when (e1.IsException()) { } try { dir.Dispose(); } - catch (Exception /*e1*/) { } + catch (Exception e1) when (e1.IsException()) { } } } diff --git a/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/AnalyzingInfixSuggesterTest.cs b/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/AnalyzingInfixSuggesterTest.cs index 2231119b9c..228350b9a8 100644 --- a/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/AnalyzingInfixSuggesterTest.cs +++ b/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/AnalyzingInfixSuggesterTest.cs @@ -523,14 +523,18 @@ private class LookupThread : ThreadJob private readonly AnalyzingInfixSuggester suggester; private readonly AtomicBoolean stop; - private Exception[] error; - public LookupThread(AnalyzingInfixSuggesterTest outerInstance, AnalyzingInfixSuggester suggester, AtomicBoolean stop, Exception[] error) + public LookupThread(AnalyzingInfixSuggesterTest outerInstance, AnalyzingInfixSuggester suggester) { this.outerInstance = outerInstance; this.suggester = suggester; - this.stop = stop; - this.error = error; + this.stop = new AtomicBoolean(false); + } + + public virtual void Finish() + { + stop.Value = true; + this.Join(); } public override void Run() @@ -553,30 +557,14 @@ public override void Run() topN, allTermsRequired, doHilite); Thread.Sleep(10);// don't starve refresh()'s CPU, which sleeps every 50 bytes for 1 ms } - catch (Exception e) + catch (Exception e) when (e.IsIOException()) { - error[0] = e; - stop.Value = true; + throw RuntimeException.Create(e); } } } } - /// - /// Grab the stack trace into a string since the exception was thrown in a thread and we want the assert - /// outside the thread to show the stack trace in case of failure. - /// - private string stackTraceStr(Exception error) - { - if (error == null) - { - return ""; - } - - error.printStackTrace(); - return error.StackTrace; - } - internal class TestRandomNRTComparer : IComparer { public int Compare(Input a, Input b) @@ -615,10 +603,7 @@ public void TestRandomNRT() // Initial suggester built with nothing: suggester.Build(new InputArrayEnumerator(new Input[0])); - var stop = new AtomicBoolean(false); - Exception[] error = new Exception[] { null }; - - LookupThread lookupThread = new LookupThread(this, suggester, stop, error); + LookupThread lookupThread = new LookupThread(this, suggester); lookupThread.Start(); int iters = AtLeast(1000); @@ -706,13 +691,10 @@ public void TestRandomNRT() { Console.WriteLine("TEST: now close/reopen suggester"); } - //lookupThread.Finish(); - stop.Value = true; - lookupThread.Join(); - Assert.Null(error[0], "Unexpcted exception at retry : \n" + stackTraceStr(error[0])); + lookupThread.Finish(); suggester.Dispose(); suggester = new AnalyzingInfixSuggester(TEST_VERSION_CURRENT, NewFSDirectory(tempDir), a, a, minPrefixChars); //LUCENENET TODO: add extra false param at version 4.11.0 - lookupThread = new LookupThread(this, suggester, stop, error); + lookupThread = new LookupThread(this, suggester); lookupThread.Start(); visibleUpto = inputs.size(); @@ -849,10 +831,7 @@ public void TestRandomNRT() } } - //lookupThread.finish(); - stop.Value = true; - lookupThread.Join(); - Assert.Null(error[0], "Unexpcted exception at retry : \n" + stackTraceStr(error[0])); + lookupThread.Finish(); } finally { @@ -992,7 +971,7 @@ public void TestNRTWithParallelAdds() suggester.Refresh(); fail("Cannot call refresh on an suggester when no docs are added to the index"); } - catch (InvalidOperationException) + catch (Exception e) when (e.IsIllegalStateException()) { //Expected } @@ -1038,9 +1017,7 @@ public void IndexDocument(AnalyzingInfixSuggester suggester, String key) { suggester.Add(new BytesRef(key), null, 10, null); } -#pragma warning disable CS0168 // Variable is declared but never used - catch (IOException e) -#pragma warning restore CS0168 // Variable is declared but never used + catch (Exception e) when (e.IsIOException()) { fail("Could not build suggest dictionary correctly"); } diff --git a/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/AnalyzingSuggesterTest.cs b/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/AnalyzingSuggesterTest.cs index c869b8810f..34d1e73d46 100644 --- a/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/AnalyzingSuggesterTest.cs +++ b/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/AnalyzingSuggesterTest.cs @@ -1475,7 +1475,7 @@ public void TestIllegalLookupArgument() suggester.DoLookup("а\u001E", false, 3); fail("should throw IllegalArgumentException"); } - catch (ArgumentException /*e*/) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -1484,7 +1484,7 @@ public void TestIllegalLookupArgument() suggester.DoLookup("а\u001F", false, 3); fail("should throw IllegalArgumentException"); } - catch (ArgumentException /*e*/) + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } @@ -1500,5 +1500,25 @@ internal static IEnumerable Shuffle(params Input[] values) asList.Shuffle(Random); return asList; } + + // LUCENENET TODO: This is a test from Lucene 4.8.1 that currently produces a stack overflow + //// TODO: we need BaseSuggesterTestCase? + //[Test] + //public void TestTooLongSuggestion() + //{ + // Analyzer a = new MockAnalyzer(Random); + // AnalyzingSuggester suggester = new AnalyzingSuggester(a); + // String bigString = TestUtil.RandomSimpleString(Random, 60000, 60000); + // try + // { + // suggester.Build(new InputArrayEnumerator(new Input[] { + // new Input(bigString, 7)})); + // fail("did not hit expected exception"); + // } + // catch (Exception iae) when (iae.IsIllegalArgumentException()) + // { + // // expected + // } + //} } } diff --git a/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/TestFreeTextSuggester.cs b/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/TestFreeTextSuggester.cs index e4ab707407..1978e503cb 100644 --- a/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/TestFreeTextSuggester.cs +++ b/src/Lucene.Net.Tests.Suggest/Suggest/Analyzing/TestFreeTextSuggester.cs @@ -101,7 +101,7 @@ public void TestIllegalByteDuringBuild() sug.Build(new InputArrayEnumerator(keys)); fail("did not hit expected exception"); } - catch (ArgumentException /*iae*/) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -123,7 +123,7 @@ public void TestIllegalByteDuringQuery() sug.DoLookup("foo\u001eb", 10); fail("did not hit expected exception"); } - catch (ArgumentException /*iae*/) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -152,9 +152,9 @@ public bool MoveNext() { doc = lfd.NextDoc(); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } if (doc == null) { @@ -245,7 +245,7 @@ public void TestEmptyString() sug.DoLookup("", 10); fail("did not hit exception"); } - catch (ArgumentException /*iae*/) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests.Suggest/Suggest/Fst/BytesRefSortersTest.cs b/src/Lucene.Net.Tests.Suggest/Suggest/Fst/BytesRefSortersTest.cs index 92a277c32a..b28d3e91e2 100644 --- a/src/Lucene.Net.Tests.Suggest/Suggest/Fst/BytesRefSortersTest.cs +++ b/src/Lucene.Net.Tests.Suggest/Suggest/Fst/BytesRefSortersTest.cs @@ -55,7 +55,7 @@ private void Check(IBytesRefSorter sorter) sorter.Add(new BytesRef(new byte[1])); fail("expected contract violation."); } - catch (InvalidOperationException /*e*/) + catch (Exception e) when (e.IsIllegalStateException()) { // Expected. } diff --git a/src/Lucene.Net.Tests.Suggest/Suggest/LookupBenchmarkTest.cs b/src/Lucene.Net.Tests.Suggest/Suggest/LookupBenchmarkTest.cs index 741bbd6dc9..c620752f2c 100644 --- a/src/Lucene.Net.Tests.Suggest/Suggest/LookupBenchmarkTest.cs +++ b/src/Lucene.Net.Tests.Suggest/Suggest/LookupBenchmarkTest.cs @@ -174,7 +174,7 @@ internal Lookup BuildLookup(Type cls, Input[] input) //lookup = cls.newInstance(); lookup = (Lookup)Activator.CreateInstance(cls); } - catch (MissingMethodException /*e*/) + catch (Exception e) when (e.IsInstantiationException()) { Analyzer a = new MockAnalyzer(random, MockTokenizer.KEYWORD, false); if (cls == typeof(AnalyzingInfixSuggester)) @@ -302,11 +302,10 @@ private BenchmarkResult Measure(ICallable callable) } return new BenchmarkResult(times, warmup, rounds); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - Console.WriteLine(e.StackTrace); - //e.printStackTrace(); - throw new Exception(e.Message, e); + e.printStackTrace(); + throw RuntimeException.Create(e); } } diff --git a/src/Lucene.Net.Tests.TestFramework/Store/TestMockDirectoryWrapper.cs b/src/Lucene.Net.Tests.TestFramework/Store/TestMockDirectoryWrapper.cs index 401e970b02..ee9e1e2307 100644 --- a/src/Lucene.Net.Tests.TestFramework/Store/TestMockDirectoryWrapper.cs +++ b/src/Lucene.Net.Tests.TestFramework/Store/TestMockDirectoryWrapper.cs @@ -102,7 +102,7 @@ public void TestDiskFull() fail("should have failed on disk full"); } #pragma warning disable 168 - catch (IOException e) + catch (Exception e) #pragma warning restore 168 { // expected @@ -128,7 +128,7 @@ public void TestDiskFull() fail("should have failed on disk full"); } #pragma warning disable 168 - catch (IOException e) + catch (Exception e) #pragma warning restore 168 { // expected @@ -234,12 +234,7 @@ protected override void Dispose(bool disposing) // { // @in = dir.OpenInput("foo", IOContext.DEFAULT); // } - // catch (FileNotFoundException) - // { - // // ok - // changed = true; - // } - // catch (DirectoryNotFoundException) // LUCENENET specific: Need to catch when the directory is not found + // catch (Exception e) when (e.IsNoSuchFileExceptionOrFileNotFoundException()) // { // // ok // changed = true; @@ -253,7 +248,7 @@ protected override void Dispose(bool disposing) // { // x = @in.ReadInt32(); // } - // catch (EndOfStreamException) + // catch (Exception e) when (e.IsEOFException()) // { // changed = true; // break; @@ -281,7 +276,7 @@ public void TestAbuseClosedIndexInput() } // @out.close(); IndexInput @in = dir.OpenInput("foo", IOContext.DEFAULT); @in.Dispose(); - Assert.Throws(() => @in.ReadByte()); + Assert.Throws(() => @in.ReadByte()); } // LUCENENET: This test compiles, but is not compatible with 4.8.0 (tested in Java Lucene), as it was ported from 8.2.0 diff --git a/src/Lucene.Net.Tests._J-S/Lucene.Net.Tests._J-S.csproj b/src/Lucene.Net.Tests._J-S/Lucene.Net.Tests._J-S.csproj index 5cfeed24e2..6435f6a4e4 100644 --- a/src/Lucene.Net.Tests._J-S/Lucene.Net.Tests._J-S.csproj +++ b/src/Lucene.Net.Tests._J-S/Lucene.Net.Tests._J-S.csproj @@ -33,7 +33,7 @@ - + diff --git a/src/Lucene.Net.Tests/Analysis/TestGraphTokenizers.cs b/src/Lucene.Net.Tests/Analysis/TestGraphTokenizers.cs index 60ed3d4ec8..2198e9235b 100644 --- a/src/Lucene.Net.Tests/Analysis/TestGraphTokenizers.cs +++ b/src/Lucene.Net.Tests/Analysis/TestGraphTokenizers.cs @@ -1,4 +1,4 @@ -using J2N.Text; +using J2N.Text; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Diagnostics; using NUnit.Framework; diff --git a/src/Lucene.Net.Tests/Analysis/TestNumericTokenStream.cs b/src/Lucene.Net.Tests/Analysis/TestNumericTokenStream.cs index d67fea30cb..9a0dfe8ff2 100644 --- a/src/Lucene.Net.Tests/Analysis/TestNumericTokenStream.cs +++ b/src/Lucene.Net.Tests/Analysis/TestNumericTokenStream.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Analysis.TokenAttributes; +using Lucene.Net.Analysis.TokenAttributes; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -92,7 +92,7 @@ public virtual void TestNotInitialized() stream.Reset(); Assert.Fail("reset() should not succeed."); } - catch (Exception) + catch (Exception e) when (e.IsIllegalStateException()) { // pass } @@ -102,7 +102,7 @@ public virtual void TestNotInitialized() stream.IncrementToken(); Assert.Fail("IncrementToken() should not succeed."); } - catch (Exception) + catch (Exception e) when (e.IsIllegalStateException()) { // pass } @@ -125,7 +125,7 @@ public virtual void TestCTA() stream.AddAttribute(); Assert.Fail("Succeeded to add CharTermAttribute."); } - catch (ArgumentException iae) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { Assert.IsTrue(iae.Message.StartsWith("NumericTokenStream does not support", StringComparison.Ordinal)); } @@ -134,7 +134,7 @@ public virtual void TestCTA() stream.AddAttribute(); Assert.Fail("Succeeded to add TestAttribute."); } - catch (ArgumentException iae) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { Assert.IsTrue(iae.Message.StartsWith("NumericTokenStream does not support", StringComparison.Ordinal)); } diff --git a/src/Lucene.Net.Tests/Codecs/Compressing/TestCompressingTermVectorsFormat.cs b/src/Lucene.Net.Tests/Codecs/Compressing/TestCompressingTermVectorsFormat.cs index f495fbfef9..a485b482c4 100644 --- a/src/Lucene.Net.Tests/Codecs/Compressing/TestCompressingTermVectorsFormat.cs +++ b/src/Lucene.Net.Tests/Codecs/Compressing/TestCompressingTermVectorsFormat.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -67,9 +67,7 @@ public virtual void TestNoOrds() var _ = termsEnum.Ord; Assert.Fail(); } -#pragma warning disable 168 - catch (NotSupportedException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsUnsupportedOperationException()) { // expected exception } @@ -79,9 +77,7 @@ public virtual void TestNoOrds() termsEnum.SeekExact(0); Assert.Fail(); } -#pragma warning disable 168 - catch (NotSupportedException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsUnsupportedOperationException()) { // expected exception } diff --git a/src/Lucene.Net.Tests/Document/TestDocument.cs b/src/Lucene.Net.Tests/Document/TestDocument.cs index 6b244ae1b3..7f4abad14c 100644 --- a/src/Lucene.Net.Tests/Document/TestDocument.cs +++ b/src/Lucene.Net.Tests/Document/TestDocument.cs @@ -1,4 +1,4 @@ -using J2N.Text; +using J2N.Text; using NUnit.Framework; using System; using System.IO; @@ -151,9 +151,7 @@ public virtual void TestConstructorExceptions() new Field("name", "value", new FieldType()); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -166,9 +164,7 @@ public virtual void TestConstructorExceptions() new Field("name", "value", ft2); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -366,7 +362,15 @@ public virtual void TestFieldSetValue() [Test] public virtual void TestInvalidFields() { - Assert.Throws(() => { new Field("foo", new MockTokenizer(new StreamReader(File.Open("", FileMode.Open))), StringField.TYPE_STORED); }); + try + { + new Field("foo", new MockTokenizer(new StreamReader(File.Open("", FileMode.Open))), StringField.TYPE_STORED); + fail("did not hit expected exc"); + } + catch (Exception iae) when (iae.IsIllegalArgumentException()) + { + // expected + } } // LUCENE-3682 diff --git a/src/Lucene.Net.Tests/Document/TestField.cs b/src/Lucene.Net.Tests/Document/TestField.cs index eabda5bdaf..08be5b7b1d 100644 --- a/src/Lucene.Net.Tests/Document/TestField.cs +++ b/src/Lucene.Net.Tests/Document/TestField.cs @@ -1,4 +1,4 @@ -using J2N.Globalization; +using J2N.Globalization; using J2N.Text; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Standard; @@ -454,9 +454,7 @@ private void TrySetByteValue(Field f) f.SetByteValue((byte)10); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -469,9 +467,7 @@ private void TrySetBytesValue(Field f) f.SetBytesValue(new byte[] { 5, 5 }); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -484,9 +480,7 @@ private void TrySetBytesRefValue(Field f) f.SetBytesValue(new BytesRef("bogus")); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -499,9 +493,7 @@ private void TrySetDoubleValue(Field f) f.SetDoubleValue(double.MaxValue); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -514,9 +506,7 @@ private void TrySetIntValue(Field f) f.SetInt32Value(int.MaxValue); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -529,9 +519,7 @@ private void TrySetLongValue(Field f) f.SetInt64Value(long.MaxValue); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -544,9 +532,7 @@ private void TrySetFloatValue(Field f) f.SetSingleValue(float.MaxValue); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -559,9 +545,7 @@ private void TrySetReaderValue(Field f) f.SetReaderValue(new StringReader("BOO!")); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -574,9 +558,7 @@ private void TrySetShortValue(Field f) f.SetInt16Value(short.MaxValue); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -589,9 +571,7 @@ private void TrySetStringValue(Field f) f.SetStringValue("BOO!"); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -604,9 +584,7 @@ private void TrySetTokenStreamValue(Field f) f.SetTokenStream(new CannedTokenStream(new Token("foo", 0, 3))); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -619,9 +597,7 @@ private void TrySetBoost(Field f) f.Boost = 5.0f; Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests/Index/Test2BDocs.cs b/src/Lucene.Net.Tests/Index/Test2BDocs.cs index c1bcdd1b11..8b9d224fca 100644 --- a/src/Lucene.Net.Tests/Index/Test2BDocs.cs +++ b/src/Lucene.Net.Tests/Index/Test2BDocs.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -66,9 +66,7 @@ public virtual void TestOverflow() new MultiReader(subReaders); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests/Index/Test2BTerms.cs b/src/Lucene.Net.Tests/Index/Test2BTerms.cs index 3398ad29ce..3a88aa946f 100644 --- a/src/Lucene.Net.Tests/Index/Test2BTerms.cs +++ b/src/Lucene.Net.Tests/Index/Test2BTerms.cs @@ -133,7 +133,7 @@ public override void CopyTo(IAttribute target) public override object Clone() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } @@ -168,7 +168,7 @@ public virtual void Test2BTerms_Mem() { if ("Lucene3x".Equals(Codec.Default.Name, StringComparison.Ordinal)) { - throw new Exception("this test cannot run with PreFlex codec"); + throw RuntimeException.Create("this test cannot run with PreFlex codec"); } Console.WriteLine("Starting Test2B"); long TERM_COUNT = ((long)int.MaxValue) + 100000000; diff --git a/src/Lucene.Net.Tests/Index/TestAddIndexes.cs b/src/Lucene.Net.Tests/Index/TestAddIndexes.cs index 395eb13bdb..b37f10af0a 100644 --- a/src/Lucene.Net.Tests/Index/TestAddIndexes.cs +++ b/src/Lucene.Net.Tests/Index/TestAddIndexes.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Attributes; using Lucene.Net.Codecs; using Lucene.Net.Documents; @@ -310,9 +310,7 @@ public virtual void TestAddSelf() writer.AddIndexes(aux, dir); Assert.IsTrue(false); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { Assert.AreEqual(100, writer.MaxDoc); } @@ -713,7 +711,7 @@ public override void Run() outerInstance.DoBody(j++, dirs); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { outerInstance.Handle(t); } @@ -948,9 +946,7 @@ internal override void Handle(Exception t) { report = !didClose; } - // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException - // in Lucene, we need to handle it here to be on the safe side. - else if (t is FileNotFoundException/* || t is NoSuchFileException*/ || t is DirectoryNotFoundException) + else if (t.IsNoSuchFileExceptionOrFileNotFoundException()) { report = !didClose; } @@ -1230,9 +1226,7 @@ public virtual void TestAddIndexMissingCodec() w.AddIndexes(toAdd); Assert.Fail("no such codec"); } -#pragma warning disable 168 - catch (ArgumentException ex) -#pragma warning restore 168 + catch (Exception ex) when (ex.IsIllegalArgumentException()) { // expected } @@ -1249,9 +1243,7 @@ public virtual void TestAddIndexMissingCodec() DirectoryReader.Open(toAdd); Assert.Fail("no such codec"); } -#pragma warning disable 168 - catch (ArgumentException ex) -#pragma warning restore 168 + catch (Exception ex) when (ex.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests/Index/TestAtomicUpdate.cs b/src/Lucene.Net.Tests/Index/TestAtomicUpdate.cs index f1eae0b737..22fec0cf78 100644 --- a/src/Lucene.Net.Tests/Index/TestAtomicUpdate.cs +++ b/src/Lucene.Net.Tests/Index/TestAtomicUpdate.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Store; @@ -65,7 +65,7 @@ public override void Run() count++; } while (Environment.TickCount < stopTime); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Console.WriteLine(Thread.CurrentThread.Name + ": exc"); Console.WriteLine(e.StackTrace); diff --git a/src/Lucene.Net.Tests/Index/TestBackwardsCompatibility.cs b/src/Lucene.Net.Tests/Index/TestBackwardsCompatibility.cs index a762f3a66a..c0dd8291ad 100644 --- a/src/Lucene.Net.Tests/Index/TestBackwardsCompatibility.cs +++ b/src/Lucene.Net.Tests/Index/TestBackwardsCompatibility.cs @@ -990,9 +990,9 @@ public virtual void TestCommandLineArgs() { upgrader = IndexUpgrader.ParseArgs(args.ToArray()); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception("unable to parse args: " + args, e); + throw RuntimeException.Create("unable to parse args: " + args, e); } upgrader.Upgrade(); diff --git a/src/Lucene.Net.Tests/Index/TestBagOfPositions.cs b/src/Lucene.Net.Tests/Index/TestBagOfPositions.cs index 35b838d41c..e4005d984b 100644 --- a/src/Lucene.Net.Tests/Index/TestBagOfPositions.cs +++ b/src/Lucene.Net.Tests/Index/TestBagOfPositions.cs @@ -204,9 +204,9 @@ public override void Run() iw.AddDocument(document); } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Index/TestBagOfPostings.cs b/src/Lucene.Net.Tests/Index/TestBagOfPostings.cs index 656764fe0b..fcdd33e290 100644 --- a/src/Lucene.Net.Tests/Index/TestBagOfPostings.cs +++ b/src/Lucene.Net.Tests/Index/TestBagOfPostings.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using J2N.Threading; using Lucene.Net.Documents; using NUnit.Framework; @@ -187,9 +187,9 @@ public override void Run() iw.AddDocument(document); } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Index/TestBinaryDocValuesUpdates.cs b/src/Lucene.Net.Tests/Index/TestBinaryDocValuesUpdates.cs index 7391e07a12..f09c3fc7d5 100644 --- a/src/Lucene.Net.Tests/Index/TestBinaryDocValuesUpdates.cs +++ b/src/Lucene.Net.Tests/Index/TestBinaryDocValuesUpdates.cs @@ -646,9 +646,7 @@ public virtual void TestUpdateNonBinaryDocValuesField() writer.UpdateBinaryDocValue(new Term("key", "doc"), "bdv", ToBytes(17L)); Assert.Fail("should not have allowed creating new fields through update"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // ok } @@ -658,9 +656,7 @@ public virtual void TestUpdateNonBinaryDocValuesField() writer.UpdateBinaryDocValue(new Term("key", "doc"), "foo", ToBytes(17L)); Assert.Fail("should not have allowed updating an existing field to binary-dv"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // ok } @@ -1181,9 +1177,7 @@ public virtual void TestUpdateOldSegments_OldFormatNotActive() writer.Dispose(); Assert.Fail("should not have succeeded to update a segment written with an old Codec"); } -#pragma warning disable 168 - catch (NotSupportedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsUnsupportedOperationException()) { writer.Rollback(); } @@ -1385,9 +1379,9 @@ public override void Run() // System.out.println("[" + Thread.currentThread().getName() + "] DONE"); success = true; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } finally { @@ -1397,11 +1391,11 @@ public override void Run() { reader.Dispose(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (success) // suppress this exception only if there was another exception { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Index/TestCodecHoldsOpenFiles.cs b/src/Lucene.Net.Tests/Index/TestCodecHoldsOpenFiles.cs index e24a8a72f1..05238df6e9 100644 --- a/src/Lucene.Net.Tests/Index/TestCodecHoldsOpenFiles.cs +++ b/src/Lucene.Net.Tests/Index/TestCodecHoldsOpenFiles.cs @@ -1,6 +1,7 @@ -using Lucene.Net.Attributes; +using Lucene.Net.Attributes; using Lucene.Net.Documents; using NUnit.Framework; +using System; using System.IO; namespace Lucene.Net.Index @@ -57,9 +58,7 @@ public virtual void Test() { d.DeleteFile(fileName); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // ignore: this means codec (correctly) is holding // the file open @@ -102,9 +101,7 @@ public virtual void TestExposeUnclosedFiles() { d.DeleteFile(fileName); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // ignore: this means codec (correctly) is holding // the file open diff --git a/src/Lucene.Net.Tests/Index/TestCodecs.cs b/src/Lucene.Net.Tests/Index/TestCodecs.cs index f38f82e17d..5771fbb088 100644 --- a/src/Lucene.Net.Tests/Index/TestCodecs.cs +++ b/src/Lucene.Net.Tests/Index/TestCodecs.cs @@ -1,4 +1,4 @@ -using J2N.Text; +using J2N.Text; using J2N.Threading; using Lucene.Net.Diagnostics; using Lucene.Net.Documents; @@ -531,10 +531,10 @@ public override void Run() { this._run(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { failed = true; - throw new Exception(t.toString(), t); + throw RuntimeException.Create(t); } } @@ -625,9 +625,7 @@ public virtual void _run() termsEnum.SeekExact(idx); success = true; } -#pragma warning disable 168 - catch (NotSupportedException uoe) -#pragma warning restore 168 + catch (Exception uoe) when (uoe.IsUnsupportedOperationException()) { // ok -- skip it } @@ -678,9 +676,7 @@ public virtual void _run() Assert.AreEqual(field.terms[i].docs.Length, termsEnum.DocFreq); Assert.IsTrue(termsEnum.Term.BytesEquals(new BytesRef(field.terms[i].text2))); } -#pragma warning disable 168 - catch (NotSupportedException uoe) -#pragma warning restore 168 + catch (Exception uoe) when (uoe.IsUnsupportedOperationException()) { } } @@ -864,9 +860,7 @@ public virtual void TestDisableImpersonation() writer.Dispose(); Assert.Fail("should not have succeeded to impersonate an old format!"); } -#pragma warning disable 168 - catch (NotSupportedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsUnsupportedOperationException()) { writer.Rollback(); } diff --git a/src/Lucene.Net.Tests/Index/TestCompoundFile.cs b/src/Lucene.Net.Tests/Index/TestCompoundFile.cs index b56f0ae2bf..3938372683 100644 --- a/src/Lucene.Net.Tests/Index/TestCompoundFile.cs +++ b/src/Lucene.Net.Tests/Index/TestCompoundFile.cs @@ -292,16 +292,7 @@ private void SetUp_2() [Test] public virtual void TestReadAfterClose() { - try - { - Demo_FSIndexInputBug(dir, "test"); - } -#pragma warning disable 168 - catch (ObjectDisposedException ode) -#pragma warning restore 168 - { - // expected - } + Demo_FSIndexInputBug(dir, "test"); } private void Demo_FSIndexInputBug(Directory fsdir, string file) @@ -336,9 +327,7 @@ private void Demo_FSIndexInputBug(Directory fsdir, string file) @in.ReadByte(); Assert.Fail("expected readByte() to throw exception"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // expected exception } @@ -568,9 +557,7 @@ public virtual void TestFileNotFound() cr.OpenInput("bogus", NewIOContext(Random)); Assert.Fail("File not found"); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { /* success */ //System.out.println("SUCCESS: File Not Found: " + e); @@ -594,9 +581,7 @@ public virtual void TestReadPastEOF() @is.ReadByte(); Assert.Fail("Single byte read past end of file"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { /* success */ //System.out.println("SUCCESS: single byte read past end of file: " + e); @@ -608,9 +593,7 @@ public virtual void TestReadPastEOF() @is.ReadBytes(b, 0, 50); Assert.Fail("Block read past end of file"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { /* success */ //System.out.println("SUCCESS: block read past end of file: " + e); diff --git a/src/Lucene.Net.Tests/Index/TestConcurrentMergeScheduler.cs b/src/Lucene.Net.Tests/Index/TestConcurrentMergeScheduler.cs index 94f2d627d7..b69a02eedd 100644 --- a/src/Lucene.Net.Tests/Index/TestConcurrentMergeScheduler.cs +++ b/src/Lucene.Net.Tests/Index/TestConcurrentMergeScheduler.cs @@ -131,7 +131,7 @@ public virtual void TestFlushExceptions() } extraCount++; } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { if (Verbose) { @@ -371,12 +371,12 @@ protected override void DoMerge(MergePolicy.OneMerge merge) runningMergeCount.DecrementAndGet(); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { failed.Value = (true); m_writer.MergeFinish(merge); // LUCENENET NOTE: ThreadJob takes care of propagating the exception to the calling thread - throw new Exception(t.ToString(), t); + throw RuntimeException.Create(t); } } } diff --git a/src/Lucene.Net.Tests/Index/TestCrashCausesCorruptIndex.cs b/src/Lucene.Net.Tests/Index/TestCrashCausesCorruptIndex.cs index 772a8c87af..f76c03f3ba 100644 --- a/src/Lucene.Net.Tests/Index/TestCrashCausesCorruptIndex.cs +++ b/src/Lucene.Net.Tests/Index/TestCrashCausesCorruptIndex.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using NUnit.Framework; using System; using System.IO; @@ -151,7 +151,7 @@ private Document Document /// The marker RuntimeException that we use in lieu of an /// actual machine crash. /// - private class CrashingException : Exception + private class CrashingException : Exception, IRuntimeException // LUCENENET specific: Added IRuntimeException for identification of the Java superclass in .NET { public CrashingException(string msg) : base(msg) diff --git a/src/Lucene.Net.Tests/Index/TestCustomNorms.cs b/src/Lucene.Net.Tests/Index/TestCustomNorms.cs index bdce4e48e6..ddf42e9615 100644 --- a/src/Lucene.Net.Tests/Index/TestCustomNorms.cs +++ b/src/Lucene.Net.Tests/Index/TestCustomNorms.cs @@ -133,12 +133,12 @@ public override long ComputeNorm(FieldInvertState state) public override SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override SimScorer GetSimScorer(SimWeight weight, AtomicReaderContext context) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } diff --git a/src/Lucene.Net.Tests/Index/TestDeletionPolicy.cs b/src/Lucene.Net.Tests/Index/TestDeletionPolicy.cs index 9db32e1eb9..1d61b4e828 100644 --- a/src/Lucene.Net.Tests/Index/TestDeletionPolicy.cs +++ b/src/Lucene.Net.Tests/Index/TestDeletionPolicy.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; @@ -187,7 +187,7 @@ internal virtual void DoDeletes(IList commits, bool isCommit) string fileName = ((IndexCommit)commits[commits.Count - 1]).SegmentsFileName; if (seen.Contains(fileName)) { - throw new Exception("onCommit was called twice on the same commit point: " + fileName); + throw RuntimeException.Create("OnCommit was called twice on the same commit point: " + fileName); } seen.Add(fileName); numOnCommit++; @@ -333,9 +333,7 @@ public virtual void TestExpirationTimeDeletionPolicy() Assert.IsTrue(lastDeleteTime - modTime <= leeway, "commit point was older than " + SECONDS + " seconds (" + (lastDeleteTime - modTime) + " msec) but did not get deleted "); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // OK break; @@ -645,7 +643,7 @@ public virtual void TestKeepLastNDeletionPolicy() Assert.Fail("should have failed on commits prior to last " + N); } } - catch (IOException /*e*/) + catch (Exception e) when (e.IsIOException()) { if (i != N) { @@ -765,7 +763,7 @@ public virtual void TestKeepLastNDeletionPolicyWithCreates() Assert.Fail("should have failed on commits before last " + N); } } - catch (IOException /*e*/) + catch (Exception e) when (e.IsIOException()) { if (i != N) { diff --git a/src/Lucene.Net.Tests/Index/TestDirectoryReader.cs b/src/Lucene.Net.Tests/Index/TestDirectoryReader.cs index dbdf310c79..cab193b54a 100644 --- a/src/Lucene.Net.Tests/Index/TestDirectoryReader.cs +++ b/src/Lucene.Net.Tests/Index/TestDirectoryReader.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Search; @@ -429,7 +429,7 @@ public virtual void TestBinaryFields() try { DirectoryReader.Open(fileDirName); Assert.Fail("opening DirectoryReader on empty directory failed to produce FileNotFoundException/NoSuchFileException"); - } catch (FileNotFoundException | NoSuchFileException e) { + } catch (Exception e) when (e.IsNoSuchFileExceptionOrFileNotFoundException()) { // GOOD } rmDir(fileDirName); @@ -477,15 +477,7 @@ public virtual void TestOpenReaderAfterDelete() DirectoryReader.Open(dir); Assert.Fail("expected FileNotFoundException/NoSuchFileException"); } -#pragma warning disable 168 - catch (FileNotFoundException /*| NoSuchFileException*/ e) -#pragma warning restore 168 - { - // expected - } - // 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()) { // expected } @@ -498,15 +490,7 @@ public virtual void TestOpenReaderAfterDelete() DirectoryReader.Open(dir); Assert.Fail("expected FileNotFoundException/NoSuchFileException"); } -#pragma warning disable 168 - catch (FileNotFoundException /*| NoSuchFileException*/ e) -#pragma warning restore 168 - { - // expected - } - // 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()) { // expected } @@ -780,9 +764,7 @@ public virtual void TestNoDir() DirectoryReader.Open(dir); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (DirectoryNotFoundException nsde) -#pragma warning restore 168 + catch (Exception nsde) when (nsde.IsNoSuchDirectoryException()) { // expected } @@ -906,9 +888,7 @@ public virtual void TestNoTermsIndex() r.DocFreq(new Term("field", "f")); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } @@ -932,9 +912,7 @@ public virtual void TestNoTermsIndex() ctx.Reader.DocFreq(new Term("field", "f")); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } @@ -1163,9 +1141,7 @@ public virtual void TestOOBDocID() r.Document(1); Assert.Fail("did not hit exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // expected } @@ -1244,7 +1220,7 @@ public override void Run() } Assert.IsFalse(toInc.TryIncRef()); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { failed = e; } @@ -1314,9 +1290,7 @@ public virtual void TestBackwards() r.DocFreq(new Term("field", "f")); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } @@ -1330,9 +1304,7 @@ public virtual void TestBackwards() r.DocFreq(new Term("field", "f")); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } diff --git a/src/Lucene.Net.Tests/Index/TestDirectoryReaderReopen.cs b/src/Lucene.Net.Tests/Index/TestDirectoryReaderReopen.cs index a9211840d2..1597167bc2 100644 --- a/src/Lucene.Net.Tests/Index/TestDirectoryReaderReopen.cs +++ b/src/Lucene.Net.Tests/Index/TestDirectoryReaderReopen.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Support; @@ -503,7 +503,7 @@ public override void Run() { this.task.Run(); } - catch (Exception r) + catch (Exception r) when (r.IsThrowable()) { Console.WriteLine(r.StackTrace); this.error = r; diff --git a/src/Lucene.Net.Tests/Index/TestDocInverterPerFieldErrorInfo.cs b/src/Lucene.Net.Tests/Index/TestDocInverterPerFieldErrorInfo.cs index 1ff88a5f41..7d8e280581 100644 --- a/src/Lucene.Net.Tests/Index/TestDocInverterPerFieldErrorInfo.cs +++ b/src/Lucene.Net.Tests/Index/TestDocInverterPerFieldErrorInfo.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Analysis; +using Lucene.Net.Analysis; using Lucene.Net.Documents; using Lucene.Net.Support.IO; using NUnit.Framework; @@ -45,7 +45,7 @@ public class TestDocInverterPerFieldErrorInfo : LuceneTestCase { private static readonly FieldType storedTextType = new FieldType(TextField.TYPE_NOT_STORED); - private class BadNews : Exception + private class BadNews : Exception, IRuntimeException // LUCENENET specific: Added IRuntimeException for identification of the Java superclass in .NET { internal BadNews(string message) : base(message) diff --git a/src/Lucene.Net.Tests/Index/TestDocValuesIndexing.cs b/src/Lucene.Net.Tests/Index/TestDocValuesIndexing.cs index 1a5da9c0a0..c271315081 100644 --- a/src/Lucene.Net.Tests/Index/TestDocValuesIndexing.cs +++ b/src/Lucene.Net.Tests/Index/TestDocValuesIndexing.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using J2N.Threading.Atomic; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; @@ -128,9 +128,7 @@ public virtual void TestMultiValuedDocValuesField() w.AddDocument(doc); Assert.Fail("didn't hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -166,9 +164,7 @@ public virtual void TestDifferentTypedDocValuesField() w.AddDocument(doc); Assert.Fail("didn't hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -204,9 +200,7 @@ public virtual void TestDifferentTypedDocValuesField2() w.AddDocument(doc); Assert.Fail("didn't hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -301,9 +295,7 @@ public virtual void TestMixedTypesSameDocument() { w.AddDocument(doc); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -327,9 +319,7 @@ public virtual void TestMixedTypesDifferentDocuments() { w.AddDocument(doc); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -355,9 +345,7 @@ public virtual void TestAddSortedTwice() iwriter.AddDocument(doc); Assert.Fail("didn't hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -384,9 +372,7 @@ public virtual void TestAddBinaryTwice() iwriter.AddDocument(doc); Assert.Fail("didn't hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // expected } @@ -413,9 +399,7 @@ public virtual void TestAddNumericTwice() iwriter.AddDocument(doc); Assert.Fail("didn't hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -444,9 +428,7 @@ public virtual void TestTooLargeSortedBytes() iwriter.AddDocument(doc); Assert.Fail("did not get expected exception"); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -475,9 +457,7 @@ public virtual void TestTooLargeTermSortedSetBytes() iwriter.AddDocument(doc); Assert.Fail("did not get expected exception"); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } @@ -502,9 +482,7 @@ public virtual void TestMixedTypesDifferentSegments() { w.AddDocument(doc); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -620,16 +598,14 @@ public override void Run() startingGun.Wait(); w.AddDocument(doc); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected hitExc.Value = (true); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } @@ -656,9 +632,7 @@ public virtual void TestMixedTypesViaAddIndexes() { w.AddIndexes(dir2); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -668,9 +642,7 @@ public virtual void TestMixedTypesViaAddIndexes() { w.AddIndexes(new IndexReader[] { r }); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -697,9 +669,7 @@ public virtual void TestIllegalTypeChange() writer.AddDocument(doc); Assert.Fail("did not hit exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -726,9 +696,7 @@ public virtual void TestIllegalTypeChangeAcrossSegments() writer.AddDocument(doc); Assert.Fail("did not hit exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -831,9 +799,7 @@ public virtual void TestTypeChangeViaAddIndexes() writer.AddIndexes(dir); Assert.Fail("did not hit exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -865,9 +831,7 @@ public virtual void TestTypeChangeViaAddIndexesIR() writer.AddIndexes(readers); Assert.Fail("did not hit exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -899,9 +863,7 @@ public virtual void TestTypeChangeViaAddIndexes2() writer.AddDocument(doc); Assert.Fail("did not hit exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -933,9 +895,7 @@ public virtual void TestTypeChangeViaAddIndexesIR2() writer.AddDocument(doc); Assert.Fail("did not hit exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -995,9 +955,7 @@ public virtual void TestSameFieldNameForPostingAndDocValue() writer.AddDocument(doc); Assert.Fail("should not have succeeded to add a field with different DV type than what already exists"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { writer.Rollback(); } diff --git a/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs b/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs index 95abf11f4b..ac77ad1444 100644 --- a/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs +++ b/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs @@ -174,9 +174,9 @@ public override void Run() Assert.AreEqual(sorted[docID], scratch2); } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } @@ -294,9 +294,9 @@ public override void Run() docIDToID = sr.GetNumericDocValues("id"); Assert.IsNotNull(stringDVDirect); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } while (Environment.TickCount < endTime) { diff --git a/src/Lucene.Net.Tests/Index/TestDocumentsWriterStallControl.cs b/src/Lucene.Net.Tests/Index/TestDocumentsWriterStallControl.cs index ab8951431d..269ddc0840 100644 --- a/src/Lucene.Net.Tests/Index/TestDocumentsWriterStallControl.cs +++ b/src/Lucene.Net.Tests/Index/TestDocumentsWriterStallControl.cs @@ -272,16 +272,15 @@ public override void Run() { Assert.IsTrue(sync.await()); } - catch (ThreadInterruptedException /*e*/) + catch (Exception e) when (e.IsInterruptedException()) { Console.WriteLine("[Waiter] got interrupted - wait count: " + sync.waiter.CurrentCount); - //throw new ThreadInterruptedException("Thread Interrupted Exception", e); 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 e) + catch (Exception e) when (e.IsThrowable()) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); @@ -328,17 +327,18 @@ public override void Run() { Assert.IsTrue(sync.await()); } - catch (ThreadInterruptedException /*e*/) + catch (Exception e) when (e.IsInterruptedException()) { Console.WriteLine("[Updater] got interrupted - wait count: " + sync.waiter.CurrentCount); - //throw new ThreadInterruptedException("Thread Interrupted Exception", e); - 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 e) - { - Console.Write("signal failed with : " + e); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) } + // LUCENENET: Not sure why this catch block was added, but I suspect it was for debugging purposes. Commented it rather than removing it because + // there may be some value to debugging this way. + //catch (Exception e) + //{ + // Console.Write("signal failed with : " + e); + // throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) + //} sync.leftCheckpoint.Signal(); } @@ -348,7 +348,7 @@ public override void Run() } } } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); diff --git a/src/Lucene.Net.Tests/Index/TestExceedMaxTermLength.cs b/src/Lucene.Net.Tests/Index/TestExceedMaxTermLength.cs index ce85fac6c1..87e5846c2a 100644 --- a/src/Lucene.Net.Tests/Index/TestExceedMaxTermLength.cs +++ b/src/Lucene.Net.Tests/Index/TestExceedMaxTermLength.cs @@ -2,6 +2,7 @@ using NUnit.Framework; using RandomizedTesting.Generators; using System; +using System.Globalization; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Index @@ -90,9 +91,9 @@ public virtual void Test() w.AddDocument(doc); Assert.Fail("Did not get an exception from adding a monster term"); } - catch (ArgumentException e) + catch (Exception e) when (e.IsIllegalArgumentException()) { - string maxLengthMsg = Convert.ToString(IndexWriter.MAX_TERM_LENGTH); + string maxLengthMsg = Convert.ToString(IndexWriter.MAX_TERM_LENGTH, CultureInfo.InvariantCulture); string msg = e.Message; Assert.IsTrue(msg.Contains("immense term"), "IllegalArgumentException didn't mention 'immense term': " + msg); Assert.IsTrue(msg.Contains(maxLengthMsg), "IllegalArgumentException didn't mention max length (" + maxLengthMsg + "): " + msg); diff --git a/src/Lucene.Net.Tests/Index/TestFieldsReader.cs b/src/Lucene.Net.Tests/Index/TestFieldsReader.cs index c798d676f8..a4d207b118 100644 --- a/src/Lucene.Net.Tests/Index/TestFieldsReader.cs +++ b/src/Lucene.Net.Tests/Index/TestFieldsReader.cs @@ -220,11 +220,9 @@ public override object Clone() { i.Seek(GetFilePointer()); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } return i; } @@ -260,9 +258,7 @@ public virtual void TestExceptions() { reader.Document(i); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // expected exc = true; @@ -271,9 +267,7 @@ public virtual void TestExceptions() { reader.Document(i); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // expected exc = true; diff --git a/src/Lucene.Net.Tests/Index/TestFlex.cs b/src/Lucene.Net.Tests/Index/TestFlex.cs index b9288e63aa..0e0d839041 100644 --- a/src/Lucene.Net.Tests/Index/TestFlex.cs +++ b/src/Lucene.Net.Tests/Index/TestFlex.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Analysis; +using Lucene.Net.Analysis; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Store; @@ -87,9 +87,7 @@ public virtual void TestTermOrd() { Assert.AreEqual(0, terms.Ord); } -#pragma warning disable 168 - catch (NotSupportedException uoe) -#pragma warning restore 168 + catch (Exception uoe) when (uoe.IsUnsupportedOperationException()) { // ok -- codec is not required to support this op } diff --git a/src/Lucene.Net.Tests/Index/TestFlushByRamOrCountsPolicy.cs b/src/Lucene.Net.Tests/Index/TestFlushByRamOrCountsPolicy.cs index 5538ac7b4d..23665f2e8f 100644 --- a/src/Lucene.Net.Tests/Index/TestFlushByRamOrCountsPolicy.cs +++ b/src/Lucene.Net.Tests/Index/TestFlushByRamOrCountsPolicy.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using J2N.Threading.Atomic; using Lucene.Net.Diagnostics; using Lucene.Net.Index.Extensions; @@ -373,11 +373,11 @@ public override void Run() } writer.Commit(); } - catch (Exception ex) + catch (Exception ex) when (ex.IsThrowable()) { Console.WriteLine("FAILED exc:"); - Console.WriteLine(ex.StackTrace); - throw new Exception(ex.Message, ex); + ex.printStackTrace(Console.Out); + throw RuntimeException.Create(ex); } } } diff --git a/src/Lucene.Net.Tests/Index/TestForceMergeForever.cs b/src/Lucene.Net.Tests/Index/TestForceMergeForever.cs index 2783af29a4..a01cb41a3c 100644 --- a/src/Lucene.Net.Tests/Index/TestForceMergeForever.cs +++ b/src/Lucene.Net.Tests/Index/TestForceMergeForever.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using J2N.Threading.Atomic; using Lucene.Net.Index.Extensions; using NUnit.Framework; @@ -137,9 +137,9 @@ public override void Run() w.GetReader().Dispose(); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { - throw new Exception(t.Message, t); + throw RuntimeException.Create(t); } } } diff --git a/src/Lucene.Net.Tests/Index/TestIndexInput.cs b/src/Lucene.Net.Tests/Index/TestIndexInput.cs index 5b3c809269..e4c9228e3a 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexInput.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexInput.cs @@ -155,7 +155,7 @@ private void CheckReads(DataInput @is, Type expectedEx) @is.ReadVInt32(); Assert.Fail("Should throw " + expectedEx.Name); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { Assert.IsTrue(e.Message.StartsWith("Invalid VInt32", StringComparison.Ordinal)); Assert.IsTrue(expectedEx.IsInstanceOfType(e)); @@ -167,7 +167,7 @@ private void CheckReads(DataInput @is, Type expectedEx) @is.ReadVInt64(); Assert.Fail("Should throw " + expectedEx.Name); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { Assert.IsTrue(e.Message.StartsWith("Invalid VInt64", StringComparison.Ordinal)); Assert.IsTrue(expectedEx.IsInstanceOfType(e)); diff --git a/src/Lucene.Net.Tests/Index/TestIndexReaderClose.cs b/src/Lucene.Net.Tests/Index/TestIndexReaderClose.cs index 49cb950672..d717db4f97 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexReaderClose.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexReaderClose.cs @@ -72,7 +72,7 @@ public virtual void TestCloseUnderException() reader.Dispose(); Assert.Fail("expected Exception"); } - catch (InvalidOperationException ex) + catch (Exception ex) when (ex.IsIllegalStateException()) { if (throwOnClose) { @@ -89,9 +89,7 @@ public virtual void TestCloseUnderException() var aaa = reader.Fields; Assert.Fail("we are closed"); } -#pragma warning disable 168 - catch (ObjectDisposedException ex) -#pragma warning restore 168 + catch (Exception ex) when (ex.IsAlreadyClosedException()) { } @@ -123,7 +121,7 @@ protected internal override void DoClose() base.DoClose(); if (throwOnClose) { - throw new InvalidOperationException("BOOM!"); + throw IllegalStateException.Create("BOOM!"); } } } @@ -147,7 +145,7 @@ private sealed class FaultyListener : IndexReader.IReaderClosedListener { public void OnClose(IndexReader reader) { - throw new InvalidOperationException("GRRRRRRRRRRRR!"); + throw IllegalStateException.Create("GRRRRRRRRRRRR!"); } } } diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriter.cs b/src/Lucene.Net.Tests/Index/TestIndexWriter.cs index 46efc40acd..d0fd38987c 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriter.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriter.cs @@ -259,9 +259,7 @@ public virtual void TestChangesAfterClose() AddDoc(writer); Assert.Fail("did not hit ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } @@ -1031,9 +1029,7 @@ public virtual void TestNegativePositions() w.AddDocument(doc); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException iea) -#pragma warning restore 168 + catch (Exception iea) when (iea.IsIllegalArgumentException()) { // expected } @@ -1167,7 +1163,6 @@ private class IndexerThreadInterrupt : ThreadJob internal IndexerThreadInterrupt(TestIndexWriter outerInstance) { this.outerInstance = outerInstance; - this.IsDebug = true; // LUCENENET: Rethrow with the original stack trace to assist with debugging this.random = new Random(LuceneTestCase.Random.Next()); // make a little directory for addIndexes // LUCENE-2239: won't work with NIOFS/MMAP @@ -1336,7 +1331,7 @@ public override void Run() allowInterrupt = true; } } - catch (ThreadInterruptedException re) + catch (ThreadInterruptedException re) // LUCENENET: This was a custom wrapper type named ThreadInterruptedException in Lucene, so leaving the catch block as is { // NOTE: important to leave this verbosity/noise // on!! this test doesn't repro easily so when @@ -1356,7 +1351,7 @@ public override void Run() break; } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Console.WriteLine("FAILED; unexpected exception"); Console.WriteLine(t.ToString()); @@ -1382,13 +1377,13 @@ public override void Run() // LUCENENET specific - there is a chance that our thread will be // interrupted here, so we need to catch and ignore that exception // when our MockDirectoryWrapper throws it. - catch (ThreadInterruptedException) + catch (Exception e) when (e.IsInterruptedException()) { // ignore } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } } @@ -1396,7 +1391,7 @@ public override void Run() { TestUtil.CheckIndex(dir); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { failed = true; Console.WriteLine("CheckIndex FAILED: unexpected exception"); @@ -1407,7 +1402,7 @@ public override void Run() using IndexReader r = DirectoryReader.Open(dir); //System.out.println("doc count=" + r.NumDocs); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { failed = true; Console.WriteLine("DirectoryReader.open FAILED: unexpected exception"); @@ -1418,17 +1413,17 @@ public override void Run() { IOUtils.Dispose(dir); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } try { IOUtils.Dispose(adder); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } @@ -1949,9 +1944,9 @@ public StringSplitTokenizer(TextReader r) { SetReader(r); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e.Message, e); } } @@ -2013,9 +2008,7 @@ public virtual void TestWickedLongTerm() w.AddDocument(doc); Assert.Fail("should have hit exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -2231,9 +2224,7 @@ public virtual void TestPrepareCommitThenClose() w.Dispose(); Assert.Fail("should have hit exception"); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } @@ -2309,17 +2300,17 @@ public AnalyzerAnonymousClass(TestIndexWriter outerInstance) protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { - throw new InvalidOperationException("don't invoke me!"); + throw IllegalStateException.Create("don't invoke me!"); } public override int GetPositionIncrementGap(string fieldName) { - throw new InvalidOperationException("don't invoke me!"); + throw IllegalStateException.Create("don't invoke me!"); } public override int GetOffsetGap(string fieldName) { - throw new InvalidOperationException("don't invoke me!"); + throw IllegalStateException.Create("don't invoke me!"); } } @@ -2592,7 +2583,7 @@ public virtual void TestIterableThrowsException() w.AddDocuments(new RandomFailingFieldIterable(docs, Random)); success = true; } - catch (Exception e) + catch (Exception e) when (e.IsRuntimeException()) { Assert.AreEqual("boom", e.Message); } @@ -2672,14 +2663,14 @@ public virtual IEnumerable Next() { if (outerInstance.Random.Next(5) == 0) { - throw new Exception("boom"); + throw RuntimeException.Create("boom"); } return DocIter.Next(); } public virtual void Remove() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } }*/ } @@ -2727,7 +2718,7 @@ public virtual void TestCorruptFirstCommit() Assert.Fail("expected exception"); } } - catch (IOException /*ioe*/) + catch (Exception ioe) when (ioe.IsIOException()) { // OpenMode_e.APPEND should throw an exception since no // index exists: diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterCommit.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterCommit.cs index 7ea3c1fcda..76b9eed0ec 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterCommit.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterCommit.cs @@ -414,10 +414,10 @@ public override void Run() } while (Environment.TickCount < endTime); r.Dispose(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { failed.Value = (true); - throw new Exception(t.Message, t); + throw RuntimeException.Create(t); } } } diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterConfig.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterConfig.cs index 44652a498e..97fb748ee2 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterConfig.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterConfig.cs @@ -309,9 +309,7 @@ public virtual void TestInvalidValues() conf.SetIndexDeletionPolicy(null); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { // ok } @@ -325,9 +323,7 @@ public virtual void TestInvalidValues() conf.SetMergeScheduler(null); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { // ok } @@ -342,9 +338,7 @@ public virtual void TestInvalidValues() conf.SetSimilarity(null); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { // ok } @@ -358,9 +352,7 @@ public virtual void TestInvalidValues() conf.SetIndexingChain(null); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { // ok } @@ -370,9 +362,7 @@ public virtual void TestInvalidValues() conf.SetMaxBufferedDeleteTerms(0); Assert.Fail("should not have succeeded to set maxBufferedDeleteTerms to 0"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // this is expected } @@ -382,9 +372,7 @@ public virtual void TestInvalidValues() conf.SetMaxBufferedDocs(1); Assert.Fail("should not have succeeded to set maxBufferedDocs to 1"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // this is expected } @@ -397,9 +385,7 @@ public virtual void TestInvalidValues() conf.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH); Assert.Fail("should not have succeeded to disable maxBufferedDocs when ramBufferSizeMB is disabled as well"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // this is expected } @@ -411,9 +397,7 @@ public virtual void TestInvalidValues() conf.SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH); Assert.Fail("should not have succeeded to disable ramBufferSizeMB when maxBufferedDocs is disabled as well"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // this is expected } @@ -424,9 +408,7 @@ public virtual void TestInvalidValues() conf.SetReaderTermsIndexDivisor(0); Assert.Fail("should not have succeeded to set termsIndexDivisor to 0"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // this is expected } @@ -438,9 +420,7 @@ public virtual void TestInvalidValues() conf.SetReaderTermsIndexDivisor(-2); Assert.Fail("should not have succeeded to set termsIndexDivisor to < -1"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // this is expected } @@ -450,9 +430,7 @@ public virtual void TestInvalidValues() conf.SetRAMPerThreadHardLimitMB(2048); Assert.Fail("should not have succeeded to set RAMPerThreadHardLimitMB to >= 2048"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // this is expected } @@ -462,9 +440,7 @@ public virtual void TestInvalidValues() conf.SetRAMPerThreadHardLimitMB(0); Assert.Fail("should not have succeeded to set RAMPerThreadHardLimitMB to 0"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // this is expected } @@ -478,9 +454,7 @@ public virtual void TestInvalidValues() conf.SetMergePolicy(null); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { // ok } diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterDelete.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterDelete.cs index 695b0a063b..97cc1b1423 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterDelete.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterDelete.cs @@ -422,9 +422,9 @@ public override void Run() } } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } finally { @@ -594,7 +594,7 @@ private void DoTestOperationsOnDiskFull(bool updates) long diskUsage = startDir.GetSizeInBytes(); long diskFree = diskUsage + 10; - IOException err = null; + Exception err = null; // LUCENENET: No need to cast to IOExcpetion bool done = false; @@ -710,7 +710,7 @@ private void DoTestOperationsOnDiskFull(bool updates) done = true; } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (Verbose) { @@ -761,7 +761,7 @@ private void DoTestOperationsOnDiskFull(bool updates) { newReader = DirectoryReader.Open(dir); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); @@ -774,7 +774,7 @@ private void DoTestOperationsOnDiskFull(bool updates) { hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); @@ -920,9 +920,7 @@ public virtual void TestErrorAfterApplyDeletes() } modifier.Commit(); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // expected failed = true; @@ -1043,7 +1041,7 @@ public virtual void TestErrorInDocsWriterAdd() { modifier.AddDocument(doc); } - catch (IOException io) + catch (Exception io) when (io.IsIOException()) { if (Verbose) { diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterExceptions.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterExceptions.cs index 65e163047d..d90a80bc6a 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterExceptions.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterExceptions.cs @@ -230,7 +230,8 @@ public override void Run() writer.UpdateDocument(idTerm, doc); } } - catch (TestPoint1Exception re) + // LUCENENET NOTE: These generally correspond to System.SystemException in .NET except for IOException types. + catch (Exception re) when (re.IsRuntimeException()) { if (Verbose) { @@ -241,7 +242,7 @@ public override void Run() { TestUtil.CheckIndex(writer.Directory); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { Console.WriteLine(Thread.CurrentThread.Name + ": unexpected exception1"); Console.WriteLine(ioe.StackTrace); @@ -249,7 +250,7 @@ public override void Run() break; } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Console.WriteLine(Thread.CurrentThread.Name + ": unexpected exception2"); Console.WriteLine(t.StackTrace); @@ -266,7 +267,7 @@ public override void Run() { writer.UpdateDocument(idTerm, doc); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Console.WriteLine(Thread.CurrentThread.Name + ": unexpected exception3"); Console.WriteLine(t.StackTrace); @@ -306,12 +307,12 @@ public void Apply(string name) Console.WriteLine(Thread.CurrentThread.Name + ": NOW FAIL: " + name); Console.WriteLine((new Exception()).StackTrace); } - throw new TestPoint1Exception(Thread.CurrentThread.Name + ": intentionally failing at " + name); + throw new TestPoint1Exception(Thread.CurrentThread.Name + ": intentionally failing at " + name); // LUCENENET TODO: Need to change this to RuntimeException once we add a custom (or flagged) exception that is created by RuntimeException.Create } } } - private class TestPoint1Exception : Exception + private class TestPoint1Exception : Exception, IRuntimeException { public TestPoint1Exception(string message) : base(message) { @@ -358,7 +359,7 @@ public virtual void TestRandomExceptions() { writer.Dispose(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Console.WriteLine("exception during close:"); Console.WriteLine(t.StackTrace); @@ -417,7 +418,7 @@ public virtual void TestRandomExceptionsThreads() { writer.Dispose(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Console.WriteLine("exception during close:"); Console.WriteLine(t.StackTrace); @@ -443,7 +444,7 @@ public void Apply(string name) { if (doFail && name.Equals("DocumentsWriterPerThread addDocument start", StringComparison.Ordinal)) { - throw new Exception("intentionally failing"); + throw RuntimeException.Create("intentionally failing"); } } } @@ -490,20 +491,15 @@ public virtual void TestExceptionDocumentsWriterInit() doc.Add(NewTextField("field", "a field", Field.Store.YES)); w.AddDocument(doc); testPoint.doFail = true; - - // LUCENENET: Don't swallow NUnit's assert exception - Assert.Throws(() => w.AddDocument(doc), "did not hit exception"); -// try -// { -// w.AddDocument(doc); -// Assert.Fail("did not hit exception"); -// } -//#pragma warning disable 168 -// catch (Exception re) -//#pragma warning restore 168 -// { -// // expected -// } + try + { + w.AddDocument(doc); + Assert.Fail("did not hit exception"); + } + catch (Exception re) when (re.IsRuntimeException()) + { + // expected + } w.Dispose(); dir.Dispose(); } @@ -532,9 +528,7 @@ public virtual void TestExceptionJustBeforeFlush() w.AddDocument(crashDoc, analyzer); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // expected } @@ -553,7 +547,7 @@ public void Apply(string name) if (doFail && name.Equals("startMergeInit", StringComparison.Ordinal)) { failed = true; - throw new Exception("intentionally failing"); + throw RuntimeException.Create("intentionally failing"); } } } @@ -583,7 +577,7 @@ public virtual void TestExceptionOnMergeInit() { w.AddDocument(doc); } - catch (Exception) + catch (Exception re) when (re.IsRuntimeException()) { break; } @@ -620,9 +614,7 @@ public virtual void TestExceptionFromTokenStream() writer.AddDocument(doc); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { } @@ -737,9 +729,7 @@ public virtual void TestDocumentsWriterAbort() { writer.AddDocument(doc); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // only one flush should fail: Assert.IsFalse(hitError); @@ -789,7 +779,7 @@ public virtual void TestDocumentsWriterExceptions() writer.AddDocument(doc); Assert.Fail("did not hit expected exception"); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { if (Verbose) { @@ -980,9 +970,7 @@ public override void Run() writer.AddDocument(doc); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { } @@ -995,7 +983,7 @@ public override void Run() } } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { lock (this) { @@ -1069,9 +1057,7 @@ public virtual void TestExceptionDuringSync() { writer.Commit(); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // expected } @@ -1119,7 +1105,7 @@ public override void Eval(MockDirectoryWrapper dir) if (!isDelete) { failOnCommit = true; - throw new Exception("now fail first"); + throw RuntimeException.Create("now fail first"); } else { @@ -1149,15 +1135,11 @@ public virtual void TestExceptionsDuringCommit() w.Dispose(); Assert.Fail(); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { Assert.Fail("expected only RuntimeException"); } -#pragma warning disable 168 - catch (Exception re) -#pragma warning restore 168 + catch (Exception re) when (re.IsRuntimeException()) { // Expected } @@ -1202,7 +1184,7 @@ public virtual void TestForceMergeExceptions() { w.ForceMerge(1); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { if (ioe.InnerException == null) { @@ -1229,9 +1211,7 @@ public virtual void TestOutOfMemoryErrorCausesCloseToFail() writer.Dispose(); Assert.Fail("OutOfMemoryError expected"); } -#pragma warning disable 168 - catch (OutOfMemoryException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsOutOfMemoryError()) { } @@ -1253,7 +1233,7 @@ public override void Message(string component, string message) { if (message.StartsWith("now flush at close", StringComparison.Ordinal) && thrown.CompareAndSet(false, true)) { - throw new OutOfMemoryException("fake OOME at " + message); + throw OutOfMemoryError.Create("fake OOME at " + message); } } @@ -1276,7 +1256,7 @@ public void Apply(string name) { if (doFail && name.Equals("rollback before checkpoint", StringComparison.Ordinal)) { - throw new Exception("intentionally failing"); + throw RuntimeException.Create("intentionally failing"); } } } @@ -1294,9 +1274,15 @@ public virtual void TestRollbackExceptionHang() AddDoc(w); testPoint.doFail = true; - // LUCENENET: Don't assert in try block - Assert.Throws(() => w.Rollback(), "did not hit intentional RuntimeException"); - + try + { + w.Rollback(); + fail("did not hit intentional RuntimeException"); + } + catch (Exception re) when (re.IsRuntimeException()) + { + // expected + } testPoint.doFail = false; w.Rollback(); dir.Dispose(); @@ -1338,7 +1324,7 @@ public virtual void TestSegmentsChecksumError() { reader = DirectoryReader.Open(dir); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { Console.WriteLine(e.StackTrace); Assert.Fail("segmentInfos failed to retry fallback to correct segments_N file"); @@ -1394,9 +1380,7 @@ public virtual void TestSimulatedCorruptIndex1() reader = DirectoryReader.Open(dir); Assert.Fail("reader did not hit IOException on opening a corrupt index"); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { } if (reader != null) @@ -1453,9 +1437,7 @@ public virtual void TestSimulatedCorruptIndex2() reader = DirectoryReader.Open(dir); Assert.Fail("reader did not hit IOException on opening a corrupt index"); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { } if (reader != null) @@ -1514,9 +1496,7 @@ public virtual void TestSimulatedCrashedWriter() { reader = DirectoryReader.Open(dir); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { Assert.Fail("reader failed to open on a crashed index"); } @@ -1526,7 +1506,7 @@ public virtual void TestSimulatedCrashedWriter() { writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetOpenMode(OpenMode.CREATE)); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { Console.WriteLine(e.StackTrace); Assert.Fail("writer failed to open on a crashed index"); @@ -1567,7 +1547,7 @@ public virtual void TestTermVectorExceptions() w.AddDocument(doc); Assert.IsFalse(field.IndexableFieldType.StoreTermVectors); } - catch (Exception e) + catch (Exception e) when (e.IsRuntimeException()) { Assert.IsTrue(e.Message.StartsWith(FailOnTermVectors.EXC_MSG, StringComparison.Ordinal)); } @@ -1592,7 +1572,7 @@ public virtual void TestTermVectorExceptions() w.AddDocument(doc); Assert.IsFalse(field.IndexableFieldType.StoreTermVectors); } - catch (Exception e) + catch (Exception e) when (e.IsRuntimeException()) { Assert.IsTrue(e.Message.StartsWith(FailOnTermVectors.EXC_MSG, StringComparison.Ordinal)); } @@ -1640,7 +1620,7 @@ public override void Eval(MockDirectoryWrapper dir) if (fail) { - throw new Exception(EXC_MSG); + throw RuntimeException.Create(EXC_MSG); } } } @@ -1684,7 +1664,7 @@ public virtual void TestAddDocsNonAbortingException() // BUG: CrashingFilter didn't Assert.Fail("did not hit expected exception"); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { // expected Assert.AreEqual(CRASH_FAIL_MESSAGE, ioe.Message); @@ -1778,7 +1758,7 @@ public virtual void TestUpdateDocsNonAbortingException() // BUG: CrashingFilter didn't Assert.Fail("did not hit expected exception"); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { // expected Assert.AreEqual(CRASH_FAIL_MESSAGE, ioe.Message); @@ -1821,7 +1801,7 @@ public override IndexInput OpenInput(string name, IOContext context) && name.StartsWith("segments_", StringComparison.Ordinal) && StackTraceHelper.DoesStackTraceContainMethod("Read")) { - throw new NotSupportedException("expected UOE"); + throw UnsupportedOperationException.Create("expected UOE"); } return base.OpenInput(name, context); @@ -1842,9 +1822,7 @@ public virtual void TestExceptionOnCtor() new IndexWriter(d, NewIndexWriterConfig(TEST_VERSION_CURRENT, null)); Assert.Fail("should have gotten a UOE"); } -#pragma warning disable 168 - catch (NotSupportedException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsUnsupportedOperationException()) { } @@ -1870,9 +1848,7 @@ public virtual void TestIllegalPositions() iw.AddDocument(doc); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected exception } @@ -1921,9 +1897,7 @@ public virtual void TestBoostOmitNorms() iw.AddDocument(list); Assert.Fail("didn't get any exception, boost silently discarded"); } -#pragma warning disable 168 - catch (NotSupportedException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsUnsupportedOperationException()) { // expected } @@ -2068,15 +2042,7 @@ public virtual void TestTooManyFileException() // Exceptions are fine - we are running out of file handlers here continue; } -#pragma warning disable 168 - catch (FileNotFoundException/* | NoSuchFileException*/ ex) -#pragma warning restore 168 - { - continue; - } - // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException - // in Lucene, we need to catch it here to be on the safe side. - catch (DirectoryNotFoundException) + catch (Exception ex) when (ex.IsNoSuchFileExceptionOrFileNotFoundException()) { continue; } @@ -2252,7 +2218,7 @@ public virtual void TestNoLostDeletesOrUpdates() w = null; } } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { // FakeIOException can be thrown from mergeMiddle, in which case IW // registers it before our CMS gets to suppress it. IW.forceMerge later @@ -2449,7 +2415,7 @@ public virtual void TestExceptionDuringRollback() iw.Rollback(); Assert.Fail(); } - catch (Exception expected) + catch (Exception expected) when (expected.IsRuntimeException()) { Assert.AreEqual("BOOM!", expected.Message); } @@ -2481,7 +2447,7 @@ public override void Message(string component, string message) { if (messageToFailOn.Equals(message, StringComparison.Ordinal)) { - throw new Exception("BOOM!"); + throw RuntimeException.Create("BOOM!"); } } diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterLockRelease.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterLockRelease.cs index 8f213792d4..4c22c52ea0 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterLockRelease.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterLockRelease.cs @@ -1,5 +1,6 @@ -using Lucene.Net.Index.Extensions; +using Lucene.Net.Index.Extensions; using NUnit.Framework; +using System; using System.IO; namespace Lucene.Net.Index @@ -41,41 +42,13 @@ public virtual void TestIndexWriterLockRelease_Mem() { new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.APPEND)); } -#pragma warning disable 168 - catch (FileNotFoundException /*| NoSuchFileException*/ e) -#pragma warning restore 168 + catch (Exception e) when (e.IsNoSuchFileExceptionOrFileNotFoundException()) { try { new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.APPEND)); } -#pragma warning disable 168 - catch (FileNotFoundException /*| NoSuchFileException*/ e1) -#pragma warning restore 168 - { - } - // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException - // in Lucene, we need to catch it here to be on the safe side. - catch (DirectoryNotFoundException) - { - } - } - // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException - // in Lucene, we need to catch it here to be on the safe side. - catch (DirectoryNotFoundException) - { - try - { - new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.APPEND)); - } -#pragma warning disable 168 - catch (FileNotFoundException /*| NoSuchFileException*/ e1) -#pragma warning restore 168 - { - } - // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException - // in Lucene, we need to catch it here to be on the safe side. - catch (DirectoryNotFoundException) + catch (Exception e1) when (e1.IsNoSuchFileExceptionOrFileNotFoundException()) { } } diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterMergePolicy.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterMergePolicy.cs index c04b652a6e..6440363205 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterMergePolicy.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterMergePolicy.cs @@ -300,9 +300,7 @@ private void AssertSetters(MergePolicy lmp) lmp.MaxCFSSegmentSizeMB = -2.0; Assert.Fail("Didn't throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // pass } diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterMerging.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterMerging.cs index c925740d60..4245c2cba9 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterMerging.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterMerging.cs @@ -1,10 +1,11 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; using System.Collections.Generic; +using System.Runtime.ExceptionServices; using System.Threading; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; @@ -409,7 +410,7 @@ public virtual void TestNoWaitClose() if (failure.Count > 0) { - throw failure[0]; + ExceptionDispatchInfo.Capture(failure[0]).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } t1.Start(); @@ -457,9 +458,7 @@ public override void Run() { finalWriter.AddDocument(doc); } -#pragma warning disable 168 - catch (ObjectDisposedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsAlreadyClosedException()) { done = true; break; @@ -471,7 +470,7 @@ public override void Run() done = true; break; } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Console.WriteLine(e.StackTrace); failure.Add(e); diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterNRTIsCurrent.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterNRTIsCurrent.cs index 166c84f3b5..1befc555f4 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterNRTIsCurrent.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterNRTIsCurrent.cs @@ -154,7 +154,7 @@ public override void Run() } } } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { failed = e; } @@ -171,9 +171,7 @@ public override void Run() { currentReader.DecRef(); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { } } @@ -204,7 +202,7 @@ public override void Run() { latch.Wait(); } - catch (ThreadInterruptedException e) + catch (Exception e) when (e.IsInterruptedException()) { failed = e; return; @@ -224,7 +222,7 @@ public override void Run() Assert.IsFalse(current); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { if (Verbose) { @@ -240,7 +238,7 @@ public override void Run() { reader.DecRef(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (failed == null) { diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterOnDiskFull.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterOnDiskFull.cs index cbe0089fa9..cf272fe6cc 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterOnDiskFull.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterOnDiskFull.cs @@ -98,7 +98,7 @@ public virtual void TestAddDocumentOnDiskFull() } writer.Commit(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (Verbose) { @@ -128,7 +128,7 @@ public virtual void TestAddDocumentOnDiskFull() } writer.Dispose(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (Verbose) { @@ -299,7 +299,7 @@ public virtual void TestAddIndexOnDiskFull() // Make a new dir that will enforce disk usage: MockDirectoryWrapper dir = new MockDirectoryWrapper(Random, new RAMDirectory(startDir, NewIOContext(Random))); indWriter = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetOpenMode(OpenMode.APPEND).SetMergePolicy(NewLogMergePolicy(false))); - IOException err = null; + Exception err = null; // LUCENENET: No need to cast to IOExcpetion IMergeScheduler ms = indWriter.Config.MergeScheduler; for (int x = 0; x < 2; x++) @@ -420,7 +420,7 @@ public virtual void TestAddIndexOnDiskFull() done = true; } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { success = false; err = e; @@ -455,7 +455,7 @@ public virtual void TestAddIndexOnDiskFull() { reader = DirectoryReader.Open(dir); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { Console.WriteLine(e.StackTrace); Assert.Fail(testName + ": exception when creating IndexReader: " + e); @@ -484,7 +484,7 @@ public virtual void TestAddIndexOnDiskFull() { hits = searcher.Search(new TermQuery(searchTerm), null, END_COUNT).ScoreDocs; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { Console.WriteLine(e.StackTrace); Assert.Fail(testName + ": exception when searching: " + e); @@ -618,9 +618,7 @@ public virtual void TestCorruptionAfterDiskFullDuringMerge() w.Commit(); Assert.Fail("fake disk full IOExceptions not hit"); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // expected Assert.IsTrue(ftdm.didFail1 || ftdm.didFail2); @@ -653,7 +651,7 @@ public virtual void TestImmediateDiskFull() writer.AddDocument(doc); Assert.Fail("did not hit disk full"); } - catch (IOException) + catch (Exception ioe) when (ioe.IsIOException()) { } // Without fix for LUCENE-1130: this call will hang: @@ -662,7 +660,7 @@ public virtual void TestImmediateDiskFull() writer.AddDocument(doc); Assert.Fail("did not hit disk full"); } - catch (IOException) + catch (Exception ioe) when (ioe.IsIOException()) { } try @@ -670,7 +668,7 @@ public virtual void TestImmediateDiskFull() writer.Dispose(false); Assert.Fail("did not hit disk full"); } - catch (IOException) + catch (Exception ioe) when (ioe.IsIOException()) { } diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterOnJRECrash.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterOnJRECrash.cs index fbcec4263f..02894c5995 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterOnJRECrash.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterOnJRECrash.cs @@ -108,7 +108,7 @@ // { // Thread.Sleep(CrashTime); // } -// catch (ThreadInterruptedException e) +// catch (Exception e) when (e.IsInterruptedException()) // { // } // outerInstance.CrashJRE(); @@ -190,7 +190,7 @@ // } // } // } -// catch (IOException e) +// catch (Exception e) when (e.IsIOException()) // { // Console.Error.WriteLine("Couldn't pipe from the forked process: " + e.ToString()); // } diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterOutOfFileDescriptors.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterOutOfFileDescriptors.cs index a2e1a9314a..b3686eafb4 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterOutOfFileDescriptors.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterOutOfFileDescriptors.cs @@ -142,7 +142,7 @@ public virtual void Test() Console.WriteLine("TEST: iter=" + iter + ": success"); } } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { if (Verbose) { diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterReader.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterReader.cs index fa7c92cc42..a43ca6b78a 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterReader.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterReader.cs @@ -591,7 +591,7 @@ public override void Run() //doBody(5, dirs); //} } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { outerInstance.Handle(t); } @@ -844,9 +844,7 @@ public virtual void TestAfterClose() DirectoryReader.OpenIfChanged(r); Assert.Fail("failed to hit ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ace) -#pragma warning restore 168 + catch (Exception ace) when (ace.IsAlreadyClosedException()) { // expected } @@ -965,10 +963,10 @@ public override void Run() writer.AddIndexes(dirs); writer.MaybeMerge(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { excs.Enqueue(t); - throw new Exception(t.Message, t); + throw RuntimeException.Create(t); } } while (Environment.TickCount < endTime); } @@ -1082,10 +1080,10 @@ public override void Run() writer.DeleteDocuments(new Term("field3", "b" + x)); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { excs.Enqueue(t); - throw new Exception(t.Message, t); + throw RuntimeException.Create(t); } } while (Environment.TickCount < endTime); } @@ -1282,9 +1280,7 @@ public virtual void TestNoTermsIndex() TestUtil.Docs(Random, r, "f", new BytesRef("val"), null, null, DocsFlags.NONE); Assert.Fail("should have failed to seek since terms index was not loaded."); } -#pragma warning disable 168 - catch (InvalidOperationException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalStateException()) { // expected - we didn't load the term index } diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterWithThreads.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterWithThreads.cs index fc3fc5f3d0..360142068a 100644 --- a/src/Lucene.Net.Tests/Index/TestIndexWriterWithThreads.cs +++ b/src/Lucene.Net.Tests/Index/TestIndexWriterWithThreads.cs @@ -106,7 +106,7 @@ public override void Run() writer.UpdateDocument(new Term("id", "" + (idUpto++)), doc); addCount++; } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { if (Verbose) { @@ -138,7 +138,7 @@ public override void Run() break; } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { //Console.WriteLine(t.StackTrace); if (noErrors) @@ -350,7 +350,7 @@ public virtual void TestMultipleThreadsFailure(Failure failure) writer.Dispose(false); success = true; } - catch (IOException) + catch (Exception ioe) when (ioe.IsIOException()) { failure.ClearDoFail(); writer.Dispose(false); @@ -407,7 +407,7 @@ public virtual void TestSingleThreadFailure(Failure failure) writer.Commit(); Assert.Fail("did not hit exception"); } - catch (IOException) + catch (Exception ioe) when (ioe.IsIOException()) { } failure.ClearDoFail(); @@ -641,7 +641,7 @@ public override void Run() startIndexing.Wait(); writer.AddDocument(doc); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { failed = true; failure = e; @@ -775,14 +775,14 @@ public override void Run() } writerRef.Value.Commit(); } - catch (ObjectDisposedException) - { - // ok - } - catch (NullReferenceException) + catch (Exception ace) when (ace.IsAlreadyClosedException()) { // ok } + //catch (NullReferenceException) // LUCENENET specific - NullReferenceException must be allowed to propagate so we can defensively avoid it in .NET + //{ + // // ok + //} finally { commitLock.Unlock(); @@ -798,29 +798,25 @@ public override void Run() { writerRef.Value.AddDocument(docs.NextDoc()); } - catch (ObjectDisposedException) - { - // ok - } - catch (NullReferenceException) - { - // ok - } - catch (InvalidOperationException) + catch (Exception ace) when (ace.IsAlreadyClosedException()) { // ok } - catch (AssertionException) + //catch (NullReferenceException) // LUCENENET specific - NullReferenceException must be allowed to propagate so we can defensively avoid it in .NET + //{ + // // ok + //} + catch (Exception ae) when (ae.IsAssertionError()) { // ok } break; } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { failed.Value = (true); - throw new Exception(t.Message, t); + throw RuntimeException.Create(t); } } } diff --git a/src/Lucene.Net.Tests/Index/TestLongPostings.cs b/src/Lucene.Net.Tests/Index/TestLongPostings.cs index 57f5afbc03..6171c8e28a 100644 --- a/src/Lucene.Net.Tests/Index/TestLongPostings.cs +++ b/src/Lucene.Net.Tests/Index/TestLongPostings.cs @@ -59,7 +59,7 @@ private string GetRandomTerm(string other) { continue; } - IOException priorException = null; + Exception priorException = null; // LUCENENET: No need to cast to IOExcpetion TokenStream ts = a.GetTokenStream("foo", new StringReader(s)); try { @@ -89,7 +89,7 @@ private string GetRandomTerm(string other) return s; } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { priorException = e; } diff --git a/src/Lucene.Net.Tests/Index/TestMixedDocValuesUpdates.cs b/src/Lucene.Net.Tests/Index/TestMixedDocValuesUpdates.cs index 8254664579..bd622f0bf5 100644 --- a/src/Lucene.Net.Tests/Index/TestMixedDocValuesUpdates.cs +++ b/src/Lucene.Net.Tests/Index/TestMixedDocValuesUpdates.cs @@ -424,9 +424,9 @@ public override void Run() // System.out.println("[" + Thread.currentThread().getName() + "] DONE"); success = true; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } finally { @@ -436,11 +436,11 @@ public override void Run() { reader.Dispose(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (success) // suppress this exception only if there was another exception { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Index/TestNRTReaderWithThreads.cs b/src/Lucene.Net.Tests/Index/TestNRTReaderWithThreads.cs index 4f699481ab..1b47436795 100644 --- a/src/Lucene.Net.Tests/Index/TestNRTReaderWithThreads.cs +++ b/src/Lucene.Net.Tests/Index/TestNRTReaderWithThreads.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using J2N.Threading.Atomic; using Lucene.Net.Attributes; using Lucene.Net.Index.Extensions; @@ -134,7 +134,7 @@ public override void Run() } } } - catch (Exception ex) + catch (Exception ex) when (ex.IsThrowable()) { Console.WriteLine(ex.StackTrace); this.ex = ex; diff --git a/src/Lucene.Net.Tests/Index/TestNeverDelete.cs b/src/Lucene.Net.Tests/Index/TestNeverDelete.cs index 41e4d41368..9d61305f79 100644 --- a/src/Lucene.Net.Tests/Index/TestNeverDelete.cs +++ b/src/Lucene.Net.Tests/Index/TestNeverDelete.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; @@ -151,9 +151,9 @@ public override void Run() docCount++; } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Index/TestNorms.cs b/src/Lucene.Net.Tests/Index/TestNorms.cs index da38b0bf2c..634cefdf46 100644 --- a/src/Lucene.Net.Tests/Index/TestNorms.cs +++ b/src/Lucene.Net.Tests/Index/TestNorms.cs @@ -240,12 +240,12 @@ public override long ComputeNorm(FieldInvertState state) public override SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override SimScorer GetSimScorer(SimWeight weight, AtomicReaderContext context) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } diff --git a/src/Lucene.Net.Tests/Index/TestNumericDocValuesUpdates.cs b/src/Lucene.Net.Tests/Index/TestNumericDocValuesUpdates.cs index db654d55df..924ab2c021 100644 --- a/src/Lucene.Net.Tests/Index/TestNumericDocValuesUpdates.cs +++ b/src/Lucene.Net.Tests/Index/TestNumericDocValuesUpdates.cs @@ -595,9 +595,7 @@ public virtual void TestUpdateNonNumericDocValuesField() writer.UpdateNumericDocValue(new Term("key", "doc"), "ndv", 17L); Assert.Fail("should not have allowed creating new fields through update"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // ok } @@ -607,9 +605,7 @@ public virtual void TestUpdateNonNumericDocValuesField() writer.UpdateNumericDocValue(new Term("key", "doc"), "foo", 17L); Assert.Fail("should not have allowed updating an existing field to numeric-dv"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // ok } @@ -1096,9 +1092,7 @@ public virtual void TestUpdateOldSegments() writer.Dispose(); Assert.Fail("should not have succeeded to update a segment written with an old Codec"); } -#pragma warning disable 168 - catch (NotSupportedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsUnsupportedOperationException()) { writer.Rollback(); } @@ -1299,9 +1293,9 @@ public override void Run() // System.out.println("[" + Thread.currentThread().getName() + "] DONE"); success = true; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } finally { @@ -1311,11 +1305,11 @@ public override void Run() { reader.Dispose(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (success) // suppress this exception only if there was another exception { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Index/TestOmitTf.cs b/src/Lucene.Net.Tests/Index/TestOmitTf.cs index 2fb3e0e856..c0d99cbb9c 100644 --- a/src/Lucene.Net.Tests/Index/TestOmitTf.cs +++ b/src/Lucene.Net.Tests/Index/TestOmitTf.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; @@ -360,7 +360,7 @@ public virtual void TestBasic() searcher.Search(pq, 10); Assert.Fail("did not hit expected exception"); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { Exception cause = e; // If the searcher uses an executor service, the IAE is wrapped into other exceptions @@ -368,9 +368,9 @@ public virtual void TestBasic() { cause = cause.InnerException; } - if (!(cause is InvalidOperationException)) + if (!cause.IsIllegalStateException()) { - throw new InvalidOperationException("Expected an IAE", e); + throw AssertionError.Create("Expected an IAE", e); } // else OK because positions are not indexed } diff --git a/src/Lucene.Net.Tests/Index/TestParallelAtomicReader.cs b/src/Lucene.Net.Tests/Index/TestParallelAtomicReader.cs index 3a86f621f0..3d2483d468 100644 --- a/src/Lucene.Net.Tests/Index/TestParallelAtomicReader.cs +++ b/src/Lucene.Net.Tests/Index/TestParallelAtomicReader.cs @@ -145,9 +145,7 @@ public virtual void TestCloseInnerReader() pr.Document(0); Assert.Fail("ParallelAtomicReader should be already closed because inner reader was closed!"); } -#pragma warning disable 168 - catch (ObjectDisposedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsAlreadyClosedException()) { // pass } @@ -180,9 +178,7 @@ public virtual void TestIncompatibleIndexes() new ParallelAtomicReader(ir1, ir2); Assert.Fail("didn't get exptected exception: indexes don't have same number of documents"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -192,9 +188,7 @@ public virtual void TestIncompatibleIndexes() new ParallelAtomicReader(Random.NextBoolean(), new AtomicReader[] { ir1, ir2 }, new AtomicReader[] { ir1, ir2 }); Assert.Fail("didn't get expected exception: indexes don't have same number of documents"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -260,9 +254,7 @@ public virtual void TestIgnoreStoredFields() new ParallelAtomicReader(true, new AtomicReader[0], new AtomicReader[] { ir1 }); Assert.Fail("didn't get expected exception: need a non-empty main-reader array"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // pass } diff --git a/src/Lucene.Net.Tests/Index/TestParallelCompositeReader.cs b/src/Lucene.Net.Tests/Index/TestParallelCompositeReader.cs index bae4c99b69..bb058673c7 100644 --- a/src/Lucene.Net.Tests/Index/TestParallelCompositeReader.cs +++ b/src/Lucene.Net.Tests/Index/TestParallelCompositeReader.cs @@ -249,9 +249,7 @@ public virtual void TestCloseInnerReader() psub.Document(0); Assert.Fail("Subreader should be already closed because inner reader was closed!"); } -#pragma warning disable 168 - catch (ObjectDisposedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsAlreadyClosedException()) { // pass } @@ -261,9 +259,7 @@ public virtual void TestCloseInnerReader() pr.Document(0); Assert.Fail("ParallelCompositeReader should be already closed because inner reader was closed!"); } -#pragma warning disable 168 - catch (ObjectDisposedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsAlreadyClosedException()) { // pass } @@ -295,9 +291,7 @@ public virtual void TestIncompatibleIndexes1() new ParallelCompositeReader(ir1, ir2); Assert.Fail("didn't get expected exception: indexes don't have same number of documents"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -306,9 +300,7 @@ public virtual void TestIncompatibleIndexes1() new ParallelCompositeReader(Random.NextBoolean(), ir1, ir2); Assert.Fail("didn't get expected exception: indexes don't have same number of documents"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -335,9 +327,7 @@ public virtual void TestIncompatibleIndexes2() new ParallelCompositeReader(readers); Assert.Fail("didn't get expected exception: indexes don't have same subreader structure"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -346,9 +336,7 @@ public virtual void TestIncompatibleIndexes2() new ParallelCompositeReader(Random.NextBoolean(), readers, readers); Assert.Fail("didn't get expected exception: indexes don't have same subreader structure"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -375,9 +363,7 @@ public virtual void TestIncompatibleIndexes3() new ParallelCompositeReader(readers); Assert.Fail("didn't get expected exception: indexes don't have same subreader structure"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -386,9 +372,7 @@ public virtual void TestIncompatibleIndexes3() new ParallelCompositeReader(Random.NextBoolean(), readers, readers); Assert.Fail("didn't get expected exception: indexes don't have same subreader structure"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected exception } @@ -458,9 +442,7 @@ public virtual void TestIgnoreStoredFields() new ParallelCompositeReader(true, new CompositeReader[0], new CompositeReader[] { ir1 }); Assert.Fail("didn't get expected exception: need a non-empty main-reader array"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // pass } diff --git a/src/Lucene.Net.Tests/Index/TestPayloads.cs b/src/Lucene.Net.Tests/Index/TestPayloads.cs index 5e36a16c3d..e86af35b74 100644 --- a/src/Lucene.Net.Tests/Index/TestPayloads.cs +++ b/src/Lucene.Net.Tests/Index/TestPayloads.cs @@ -1,4 +1,4 @@ -using J2N.Text; +using J2N.Text; using J2N.Threading; using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; @@ -548,10 +548,9 @@ public override void Run() writer.AddDocument(d); } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - Console.WriteLine(e.ToString()); - Console.Write(e.StackTrace); + e.printStackTrace(); Assert.Fail(e.ToString()); } } diff --git a/src/Lucene.Net.Tests/Index/TestPayloadsOnVectors.cs b/src/Lucene.Net.Tests/Index/TestPayloadsOnVectors.cs index 7460630c09..5bc884ed13 100644 --- a/src/Lucene.Net.Tests/Index/TestPayloadsOnVectors.cs +++ b/src/Lucene.Net.Tests/Index/TestPayloadsOnVectors.cs @@ -162,9 +162,7 @@ public virtual void TestPayloadsWithoutPositions() writer.AddDocument(doc); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests/Index/TestPerSegmentDeletes.cs b/src/Lucene.Net.Tests/Index/TestPerSegmentDeletes.cs index e8eac54fa5..3141b3adad 100644 --- a/src/Lucene.Net.Tests/Index/TestPerSegmentDeletes.cs +++ b/src/Lucene.Net.Tests/Index/TestPerSegmentDeletes.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Index.Extensions; +using Lucene.Net.Index.Extensions; using Lucene.Net.Support; using NUnit.Framework; using System; @@ -259,13 +259,13 @@ public virtual int[] ToDocsArray(Term term, IBits bits, IndexReader reader) public static int[] ToArray(DocsEnum docsEnum) { - IList docs = new List(); + List docs = new List(); while (docsEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { int docID = docsEnum.DocID; docs.Add(docID); } - return ArrayUtil.ToInt32Array(docs); + return docs.ToArray(); // LUCENENET: ArrayUtil.ToIntArray() call unnecessary because we aren't dealing with reference types } public class RangeMergePolicy : MergePolicy diff --git a/src/Lucene.Net.Tests/Index/TestPersistentSnapshotDeletionPolicy.cs b/src/Lucene.Net.Tests/Index/TestPersistentSnapshotDeletionPolicy.cs index 14e8a67b08..ff7c0e1a84 100644 --- a/src/Lucene.Net.Tests/Index/TestPersistentSnapshotDeletionPolicy.cs +++ b/src/Lucene.Net.Tests/Index/TestPersistentSnapshotDeletionPolicy.cs @@ -113,9 +113,7 @@ public virtual void TestMissingSnapshots() new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } @@ -136,7 +134,7 @@ public virtual void TestExceptionDuringSave() { psdp.Snapshot(); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { if (ioe.Message.Equals("now fail on purpose", StringComparison.Ordinal)) { diff --git a/src/Lucene.Net.Tests/Index/TestPostingsOffsets.cs b/src/Lucene.Net.Tests/Index/TestPostingsOffsets.cs index 16419150dd..a453fe4cc2 100644 --- a/src/Lucene.Net.Tests/Index/TestPostingsOffsets.cs +++ b/src/Lucene.Net.Tests/Index/TestPostingsOffsets.cs @@ -467,9 +467,7 @@ public virtual void TestNegativeOffsets() CheckTokens(new Token[] { MakeToken("foo", 1, -1, -1) }); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { //expected } @@ -483,9 +481,7 @@ public virtual void TestIllegalOffsets() CheckTokens(new Token[] { MakeToken("foo", 1, 1, 0) }); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { //expected } @@ -499,9 +495,7 @@ public virtual void TestBackwardsOffsets() CheckTokens(new Token[] { MakeToken("foo", 1, 0, 3), MakeToken("foo", 1, 4, 7), MakeToken("foo", 0, 3, 6) }); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests/Index/TestReaderClosed.cs b/src/Lucene.Net.Tests/Index/TestReaderClosed.cs index 3e1295b9ff..dfd1bb1379 100644 --- a/src/Lucene.Net.Tests/Index/TestReaderClosed.cs +++ b/src/Lucene.Net.Tests/Index/TestReaderClosed.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; @@ -74,9 +74,7 @@ public virtual void Test() { searcher.Search(query, 5); } -#pragma warning disable 168 - catch (ObjectDisposedException ace) -#pragma warning restore 168 + catch (Exception ace) when (ace.IsAlreadyClosedException()) { // expected } @@ -98,12 +96,12 @@ public virtual void TestReaderChaining() { searcher.Search(query, 5); } - catch (ObjectDisposedException ace) + catch (Exception ace) when (ace.IsAlreadyClosedException()) { //Assert.AreEqual("this IndexReader cannot be used anymore as one of its child readers was closed", ace.Message); // LUCENENET specific - ObjectDisposedExeption appends the type of object to the end of the message, // so we need to check the start of the message only. - assertTrue(ace.Message.StartsWith("this IndexReader cannot be used anymore as one of its child readers was closed", StringComparison.Ordinal)); + assertTrue(ace.Message.StartsWith("this IndexReader cannot be used anymore as one of its child readers was disposed.", StringComparison.Ordinal)); } finally { diff --git a/src/Lucene.Net.Tests/Index/TestRollingUpdates.cs b/src/Lucene.Net.Tests/Index/TestRollingUpdates.cs index 825a99047e..2e5d822009 100644 --- a/src/Lucene.Net.Tests/Index/TestRollingUpdates.cs +++ b/src/Lucene.Net.Tests/Index/TestRollingUpdates.cs @@ -275,9 +275,9 @@ public override void Run() open.Dispose(); } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Index/TestSegmentReader.cs b/src/Lucene.Net.Tests/Index/TestSegmentReader.cs index df9019cf67..cf4fdd04f8 100644 --- a/src/Lucene.Net.Tests/Index/TestSegmentReader.cs +++ b/src/Lucene.Net.Tests/Index/TestSegmentReader.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using System.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; @@ -177,7 +177,7 @@ public virtual void TestNorms() byte [] norms = reader.norms(DocHelper.TEXT_FIELD_1_KEY); System.out.println("Norms: " + norms); Assert.IsTrue(norms != null); - } catch (IOException e) { + } catch (Exception e) when (e.IsIOException()) { e.printStackTrace(); Assert.IsTrue(false); } @@ -235,9 +235,7 @@ public virtual void TestOutOfBoundsAccess() reader.Document(-1); Assert.Fail(); } -#pragma warning disable 168 - catch (IndexOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { } @@ -246,9 +244,7 @@ public virtual void TestOutOfBoundsAccess() reader.GetTermVectors(-1); Assert.Fail(); } -#pragma warning disable 168 - catch (IndexOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { } @@ -257,9 +253,7 @@ public virtual void TestOutOfBoundsAccess() reader.Document(numDocs); Assert.Fail(); } -#pragma warning disable 168 - catch (IndexOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { } @@ -268,9 +262,7 @@ public virtual void TestOutOfBoundsAccess() reader.GetTermVectors(numDocs); Assert.Fail(); } -#pragma warning disable 168 - catch (IndexOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { } } diff --git a/src/Lucene.Net.Tests/Index/TestSegmentTermEnum.cs b/src/Lucene.Net.Tests/Index/TestSegmentTermEnum.cs index c4a34f955c..c12ea670d3 100644 --- a/src/Lucene.Net.Tests/Index/TestSegmentTermEnum.cs +++ b/src/Lucene.Net.Tests/Index/TestSegmentTermEnum.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; @@ -97,9 +97,7 @@ public virtual void TestPrevTermAtEnd() { ordB = terms.Ord; } -#pragma warning disable 168 - catch (NotSupportedException uoe) -#pragma warning restore 168 + catch (Exception uoe) when (uoe.IsUnsupportedOperationException()) { // ok -- codec is not required to support ord reader.Dispose(); diff --git a/src/Lucene.Net.Tests/Index/TestSnapshotDeletionPolicy.cs b/src/Lucene.Net.Tests/Index/TestSnapshotDeletionPolicy.cs index 67c8012064..7cec87b801 100644 --- a/src/Lucene.Net.Tests/Index/TestSnapshotDeletionPolicy.cs +++ b/src/Lucene.Net.Tests/Index/TestSnapshotDeletionPolicy.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; @@ -136,9 +136,7 @@ private void RunTest(Random random, Directory dir) dp.Snapshot(); Assert.Fail("did not hit exception"); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } @@ -210,7 +208,7 @@ public override void Run() { writer.AddDocument(doc); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Console.WriteLine(t.StackTrace); Assert.Fail("addDocument failed"); @@ -221,9 +219,9 @@ public override void Run() { writer.Commit(); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } @@ -406,9 +404,9 @@ public override void Run() writer.Commit(); snapshots[finalI] = sdp.Snapshot(); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Index/TestStressIndexing.cs b/src/Lucene.Net.Tests/Index/TestStressIndexing.cs index fb31695ede..ee3c8b2766 100644 --- a/src/Lucene.Net.Tests/Index/TestStressIndexing.cs +++ b/src/Lucene.Net.Tests/Index/TestStressIndexing.cs @@ -66,7 +66,7 @@ public override void Run() count++; } while (Environment.TickCount < stopTime); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Console.WriteLine(Thread.CurrentThread + ": exc"); Console.WriteLine(e.StackTrace); diff --git a/src/Lucene.Net.Tests/Index/TestStressIndexing2.cs b/src/Lucene.Net.Tests/Index/TestStressIndexing2.cs index bbd6ef0ce3..22e9c3b560 100644 --- a/src/Lucene.Net.Tests/Index/TestStressIndexing2.cs +++ b/src/Lucene.Net.Tests/Index/TestStressIndexing2.cs @@ -433,7 +433,7 @@ public virtual void VerifyEquals(DirectoryReader r1, DirectoryReader r2, string { VerifyEquals(r1.Document(id1), r2.Document(id2)); } - catch (Exception /*t*/) + catch (Exception t) when (t.IsThrowable()) { Console.WriteLine("FAILED id=" + term + " id1=" + id1 + " id2=" + id2 + " term=" + term); Console.WriteLine(" d1=" + r1.Document(id1)); @@ -446,7 +446,7 @@ public virtual void VerifyEquals(DirectoryReader r1, DirectoryReader r2, string // verify term vectors are equivalent VerifyEquals(r1.GetTermVectors(id1), r2.GetTermVectors(id2)); } - catch (Exception /*e*/) + catch (Exception e) when (e.IsThrowable()) { Console.WriteLine("FAILED id=" + term + " id1=" + id1 + " id2=" + id2); Fields tv1 = r1.GetTermVectors(id1); @@ -1036,7 +1036,7 @@ public override void Run() } } } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); diff --git a/src/Lucene.Net.Tests/Index/TestStressNRT.cs b/src/Lucene.Net.Tests/Index/TestStressNRT.cs index c396928fd0..4574402cd3 100644 --- a/src/Lucene.Net.Tests/Index/TestStressNRT.cs +++ b/src/Lucene.Net.Tests/Index/TestStressNRT.cs @@ -398,11 +398,11 @@ public override void Run() } } } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Console.WriteLine(Thread.CurrentThread.Name + ": FAILED: unexpected exception"); Console.WriteLine(e.StackTrace); - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } @@ -523,12 +523,12 @@ public override void Run() r.DecRef(); } } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { operations.Value = ((int)-1L); Console.WriteLine(Thread.CurrentThread.Name + ": FAILED: unexpected exception"); Console.WriteLine(e.StackTrace); - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Index/TestTermVectorsReader.cs b/src/Lucene.Net.Tests/Index/TestTermVectorsReader.cs index 3f4579ac80..b593e0f5fb 100644 --- a/src/Lucene.Net.Tests/Index/TestTermVectorsReader.cs +++ b/src/Lucene.Net.Tests/Index/TestTermVectorsReader.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Analysis; +using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; @@ -416,7 +416,7 @@ public virtual void TestIllegalIndexableField() w.AddDocument(doc); Assert.Fail("did not hit exception"); } - catch (ArgumentException iae) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // Expected Assert.AreEqual("cannot index term vector payloads without term vector positions (field=\"field\")", iae.Message); @@ -432,7 +432,7 @@ public virtual void TestIllegalIndexableField() w.AddDocument(doc); Assert.Fail("did not hit exception"); } - catch (ArgumentException iae) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // Expected Assert.AreEqual("cannot index term vector offsets when term vectors are not indexed (field=\"field\")", iae.Message); @@ -448,7 +448,7 @@ public virtual void TestIllegalIndexableField() w.AddDocument(doc); Assert.Fail("did not hit exception"); } - catch (ArgumentException iae) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // Expected Assert.AreEqual("cannot index term vector positions when term vectors are not indexed (field=\"field\")", iae.Message); @@ -464,7 +464,7 @@ public virtual void TestIllegalIndexableField() w.AddDocument(doc); Assert.Fail("did not hit exception"); } - catch (ArgumentException iae) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // Expected Assert.AreEqual("cannot index term vector payloads when term vectors are not indexed (field=\"field\")", iae.Message); diff --git a/src/Lucene.Net.Tests/Index/TestTermVectorsWriter.cs b/src/Lucene.Net.Tests/Index/TestTermVectorsWriter.cs index ea9e81a9b7..cef2a7268b 100644 --- a/src/Lucene.Net.Tests/Index/TestTermVectorsWriter.cs +++ b/src/Lucene.Net.Tests/Index/TestTermVectorsWriter.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; @@ -192,7 +192,7 @@ public virtual void TestEndOffsetPositionWithCachingTokenFilter() Analyzer analyzer = new MockAnalyzer(Random); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer)); Document doc = new Document(); - IOException priorException = null; + Exception priorException = null; // LUCENENET: No need to cast to IOExcpetion TokenStream stream = analyzer.GetTokenStream("field", new StringReader("abcd ")); try { @@ -207,7 +207,7 @@ public virtual void TestEndOffsetPositionWithCachingTokenFilter() doc.Add(f); w.AddDocument(doc); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { priorException = e; } diff --git a/src/Lucene.Net.Tests/Index/TestThreadedForceMerge.cs b/src/Lucene.Net.Tests/Index/TestThreadedForceMerge.cs index 78b93d37f7..491aaa1c2c 100644 --- a/src/Lucene.Net.Tests/Index/TestThreadedForceMerge.cs +++ b/src/Lucene.Net.Tests/Index/TestThreadedForceMerge.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; @@ -160,7 +160,7 @@ public override void Run() writerFinal.ForceMerge(1); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { outerInstance.SetFailed(); Console.WriteLine(Thread.CurrentThread.Name + ": hit exception"); diff --git a/src/Lucene.Net.Tests/Index/TestTieredMergePolicy.cs b/src/Lucene.Net.Tests/Index/TestTieredMergePolicy.cs index 224579eabd..17f39863e7 100644 --- a/src/Lucene.Net.Tests/Index/TestTieredMergePolicy.cs +++ b/src/Lucene.Net.Tests/Index/TestTieredMergePolicy.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Attributes; +using Lucene.Net.Attributes; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Store; @@ -230,9 +230,7 @@ public virtual void TestSetters() tmp.MaxMergedSegmentMB = -2.0; Assert.Fail("Didn't throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // pass } @@ -251,9 +249,7 @@ public virtual void TestSetters() tmp.FloorSegmentMB = -2.0; Assert.Fail("Didn't throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // pass } @@ -272,9 +268,7 @@ public virtual void TestSetters() tmp.MaxCFSSegmentSizeMB = -2.0; Assert.Fail("Didn't throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // pass } diff --git a/src/Lucene.Net.Tests/Index/TestTransactionRollback.cs b/src/Lucene.Net.Tests/Index/TestTransactionRollback.cs index c41538b333..caaee32798 100644 --- a/src/Lucene.Net.Tests/Index/TestTransactionRollback.cs +++ b/src/Lucene.Net.Tests/Index/TestTransactionRollback.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; @@ -68,7 +68,7 @@ private void RollBackLast(int id) if (last == null) { - throw new Exception("Couldn't find commit point " + id); + throw RuntimeException.Create("Couldn't find commit point " + id); } IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetIndexDeletionPolicy(new RollbackDeletionPolicy(this, id)).SetIndexCommit(last)); diff --git a/src/Lucene.Net.Tests/Index/TestTransactions.cs b/src/Lucene.Net.Tests/Index/TestTransactions.cs index cc9368568f..8537f7fe98 100644 --- a/src/Lucene.Net.Tests/Index/TestTransactions.cs +++ b/src/Lucene.Net.Tests/Index/TestTransactions.cs @@ -90,7 +90,7 @@ public override void Run() DoWork(); } while (Environment.TickCount < stopTime); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Console.WriteLine(Thread.CurrentThread + ": exc"); Console.Error.WriteLine(e.StackTrace); @@ -168,7 +168,7 @@ public override void DoWork() { writer1.PrepareCommit(); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { writer1.Rollback(); writer2.Rollback(); @@ -178,7 +178,7 @@ public override void DoWork() { writer2.PrepareCommit(); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { writer1.Rollback(); writer2.Rollback(); @@ -246,7 +246,7 @@ public override void DoWork() r1 = DirectoryReader.Open(dir1); r2 = DirectoryReader.Open(dir2); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (!e.Message.Contains("on purpose")) { @@ -265,7 +265,7 @@ public override void DoWork() } if (r1.NumDocs != r2.NumDocs) { - throw new Exception("doc counts differ: r1=" + r1.NumDocs + " r2=" + r2.NumDocs); + throw RuntimeException.Create("doc counts differ: r1=" + r1.NumDocs + " r2=" + r2.NumDocs); } r1.Dispose(); r2.Dispose(); diff --git a/src/Lucene.Net.Tests/Index/TestTwoPhaseCommitTool.cs b/src/Lucene.Net.Tests/Index/TestTwoPhaseCommitTool.cs index 35ff0ce025..a9286fe431 100644 --- a/src/Lucene.Net.Tests/Index/TestTwoPhaseCommitTool.cs +++ b/src/Lucene.Net.Tests/Index/TestTwoPhaseCommitTool.cs @@ -72,7 +72,7 @@ public virtual void Commit(IDictionary commitData) commitCalled = true; if (failOnCommit) { - throw new Exception("failOnCommit"); + throw RuntimeException.Create("failOnCommit"); } } @@ -81,7 +81,7 @@ public void Rollback() rollbackCalled = true; if (failOnRollback) { - throw new Exception("failOnRollback"); + throw Error.Create("failOnRollback"); } } } @@ -127,9 +127,7 @@ public virtual void TestRollback() { TwoPhaseCommitTool.Execute(objects); } -#pragma warning disable 168 - catch (Exception t) -#pragma warning restore 168 + catch (Exception t) when (t.IsThrowable()) { anyFailure = true; } diff --git a/src/Lucene.Net.Tests/Index/TestUniqueTermCount.cs b/src/Lucene.Net.Tests/Index/TestUniqueTermCount.cs index 3c49f21255..582041ce1e 100644 --- a/src/Lucene.Net.Tests/Index/TestUniqueTermCount.cs +++ b/src/Lucene.Net.Tests/Index/TestUniqueTermCount.cs @@ -112,12 +112,12 @@ public override long ComputeNorm(FieldInvertState state) public override SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { - throw new InvalidOperationException(); + throw UnsupportedOperationException.Create(); } public override SimScorer GetSimScorer(SimWeight weight, AtomicReaderContext context) { - throw new InvalidOperationException(); + throw UnsupportedOperationException.Create(); } } } diff --git a/src/Lucene.Net.Tests/Search/JustCompileSearch.cs b/src/Lucene.Net.Tests/Search/JustCompileSearch.cs index 1bd067e51e..c04a2d9745 100644 --- a/src/Lucene.Net.Tests/Search/JustCompileSearch.cs +++ b/src/Lucene.Net.Tests/Search/JustCompileSearch.cs @@ -43,47 +43,47 @@ internal sealed class JustCompileCollector : ICollector { public void Collect(int doc) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public void SetNextReader(AtomicReaderContext context) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public void SetScorer(Scorer scorer) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } - public bool AcceptsDocsOutOfOrder => throw new NotSupportedException(UNSUPPORTED_MSG); + public bool AcceptsDocsOutOfOrder => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } internal sealed class JustCompileDocIdSet : DocIdSet { public override DocIdSetIterator GetIterator() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } internal sealed class JustCompileDocIdSetIterator : DocIdSetIterator { - public override int DocID => throw new NotSupportedException(UNSUPPORTED_MSG); + public override int DocID => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override int NextDoc() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override int Advance(int target) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override long GetCost() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -94,12 +94,12 @@ internal sealed class JustCompileExtendedFieldCacheLongParser : FieldCache.IInt6 /// public long ParseInt64(BytesRef @string) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public TermsEnum TermsEnum(Terms terms) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -107,12 +107,12 @@ internal sealed class JustCompileExtendedFieldCacheDoubleParser : FieldCache.IDo { public double ParseDouble(BytesRef term) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public TermsEnum TermsEnum(Terms terms) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -120,40 +120,40 @@ internal sealed class JustCompileFieldComparer : FieldComparer { public override int Compare(int slot1, int slot2) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override int CompareBottom(int doc) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override void Copy(int slot, int doc) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override void SetBottom(int slot) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override void SetTopValue(object value) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override FieldComparer SetNextReader(AtomicReaderContext context) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } // LUCENENET NOTE: This was value(int) in Lucene. - public override IComparable this[int slot] => throw new NotSupportedException(UNSUPPORTED_MSG); + public override IComparable this[int slot] => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override int CompareTop(int doc) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -161,7 +161,7 @@ internal sealed class JustCompileFieldComparerSource : FieldComparerSource { public override FieldComparer NewComparer(string fieldname, int numHits, int sortPos, bool reversed) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -185,7 +185,7 @@ public JustCompileFilteredDocIdSet(DocIdSet innerSet) protected override bool Match(int docid) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -198,12 +198,12 @@ public JustCompileFilteredDocIdSetIterator(DocIdSetIterator innerIter) protected override bool Match(int doc) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override long GetCost() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -211,7 +211,7 @@ internal sealed class JustCompileQuery : Query { public override string ToString(string field) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -224,26 +224,26 @@ internal JustCompileScorer(Weight weight) public override float GetScore() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } - public override int Freq => throw new NotSupportedException(UNSUPPORTED_MSG); + public override int Freq => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); - public override int DocID => throw new NotSupportedException(UNSUPPORTED_MSG); + public override int DocID => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override int NextDoc() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override int Advance(int target) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override long GetCost() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -251,17 +251,17 @@ internal sealed class JustCompileSimilarity : Similarity { public override SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override SimScorer GetSimScorer(SimWeight stats, AtomicReaderContext context) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override long ComputeNorm(FieldInvertState state) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -274,34 +274,34 @@ internal JustCompileTopDocsCollector(PriorityQueue pq) public override void Collect(int doc) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override void SetNextReader(AtomicReaderContext context) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override void SetScorer(Scorer scorer) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } - public override bool AcceptsDocsOutOfOrder => throw new NotSupportedException(UNSUPPORTED_MSG); + public override bool AcceptsDocsOutOfOrder => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override TopDocs GetTopDocs() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override TopDocs GetTopDocs(int start) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override TopDocs GetTopDocs(int start, int end) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -309,24 +309,24 @@ internal sealed class JustCompileWeight : Weight { public override Explanation Explain(AtomicReaderContext context, int doc) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } - public override Query Query => throw new NotSupportedException(UNSUPPORTED_MSG); + public override Query Query => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override void Normalize(float norm, float topLevelBoost) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override float GetValueForNormalization() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } } diff --git a/src/Lucene.Net.Tests/Search/MultiCollectorTest.cs b/src/Lucene.Net.Tests/Search/MultiCollectorTest.cs index 5c5f7c939e..910271527b 100644 --- a/src/Lucene.Net.Tests/Search/MultiCollectorTest.cs +++ b/src/Lucene.Net.Tests/Search/MultiCollectorTest.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -68,9 +68,7 @@ public virtual void TestNullCollectors() MultiCollector.Wrap(null, null); Assert.Fail("only null collectors should not be supported"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // expected } diff --git a/src/Lucene.Net.Tests/Search/Spans/JustCompileSearchSpans.cs b/src/Lucene.Net.Tests/Search/Spans/JustCompileSearchSpans.cs index 23fced5e4b..0c4b78976e 100644 --- a/src/Lucene.Net.Tests/Search/Spans/JustCompileSearchSpans.cs +++ b/src/Lucene.Net.Tests/Search/Spans/JustCompileSearchSpans.cs @@ -39,47 +39,47 @@ internal sealed class JustCompileSearchSpans internal sealed class JustCompileSpans : Spans { - public override int Doc => throw new NotSupportedException(UNSUPPORTED_MSG); + public override int Doc => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); - public override int End => throw new NotSupportedException(UNSUPPORTED_MSG); + public override int End => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override bool MoveNext() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override bool SkipTo(int target) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } - public override int Start => throw new NotSupportedException(UNSUPPORTED_MSG); + public override int Start => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override ICollection GetPayload() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } - public override bool IsPayloadAvailable => throw new NotSupportedException(UNSUPPORTED_MSG); + public override bool IsPayloadAvailable => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override long GetCost() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } internal sealed class JustCompileSpanQuery : SpanQuery { - public override string Field => throw new NotSupportedException(UNSUPPORTED_MSG); + public override string Field => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary termContexts) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override string ToString(string field) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -87,30 +87,30 @@ internal sealed class JustCompilePayloadSpans : Spans { public override ICollection GetPayload() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } - public override bool IsPayloadAvailable => throw new NotSupportedException(UNSUPPORTED_MSG); + public override bool IsPayloadAvailable => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); - public override int Doc => throw new NotSupportedException(UNSUPPORTED_MSG); + public override int Doc => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); - public override int End => throw new NotSupportedException(UNSUPPORTED_MSG); + public override int End => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override bool MoveNext() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } public override bool SkipTo(int target) { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } - public override int Start => throw new NotSupportedException(UNSUPPORTED_MSG); + public override int Start => throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); public override long GetCost() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } @@ -123,7 +123,7 @@ internal JustCompileSpanScorer(Spans spans, Weight weight, Similarity.SimScorer protected override bool SetFreqCurrentDoc() { - throw new NotSupportedException(UNSUPPORTED_MSG); + throw UnsupportedOperationException.Create(UNSUPPORTED_MSG); } } } diff --git a/src/Lucene.Net.Tests/Search/TestAutomatonQuery.cs b/src/Lucene.Net.Tests/Search/TestAutomatonQuery.cs index b7197cc0bb..1a3331f556 100644 --- a/src/Lucene.Net.Tests/Search/TestAutomatonQuery.cs +++ b/src/Lucene.Net.Tests/Search/TestAutomatonQuery.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using NUnit.Framework; using System.Threading; @@ -271,6 +271,8 @@ public override void Run() { queries[i].GetHashCode(); } + // LUCENENET: The Rethrow.rethrow() method only is for tricking the Java compiler into letting it throw a "checked" exception. + // In .NET, it is better just not to catch than deal with such nonsense. } } } diff --git a/src/Lucene.Net.Tests/Search/TestBoolean2.cs b/src/Lucene.Net.Tests/Search/TestBoolean2.cs index 20bde96996..e707b1ee17 100644 --- a/src/Lucene.Net.Tests/Search/TestBoolean2.cs +++ b/src/Lucene.Net.Tests/Search/TestBoolean2.cs @@ -353,7 +353,7 @@ public virtual void TestRandomQueries() Assert.AreEqual(mulFactor * collector.TotalHits + NUM_EXTRA_DOCS / 2, hits4.TotalHits); } } - catch (Exception) + catch (Exception e) when (e.IsException()) { // For easier debugging Console.WriteLine("failed query: " + q1); diff --git a/src/Lucene.Net.Tests/Search/TestBooleanQuery.cs b/src/Lucene.Net.Tests/Search/TestBooleanQuery.cs index 752fd423d5..ddd0db081e 100644 --- a/src/Lucene.Net.Tests/Search/TestBooleanQuery.cs +++ b/src/Lucene.Net.Tests/Search/TestBooleanQuery.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Util; using NUnit.Framework; using System; @@ -79,9 +79,7 @@ public virtual void TestException() BooleanQuery.MaxClauseCount = 0; Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // okay } diff --git a/src/Lucene.Net.Tests/Search/TestBooleanScorer.cs b/src/Lucene.Net.Tests/Search/TestBooleanScorer.cs index c39e321901..2d365ba6ea 100644 --- a/src/Lucene.Net.Tests/Search/TestBooleanScorer.cs +++ b/src/Lucene.Net.Tests/Search/TestBooleanScorer.cs @@ -255,7 +255,7 @@ public WeightAnonymousClass(CrazyMustUseBulkScorerQuery outerInstance) public override Explanation Explain(AtomicReaderContext context, int doc) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override Query Query => outerInstance; @@ -271,7 +271,7 @@ public override void Normalize(float norm, float topLevelBoost) public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override BulkScorer GetBulkScorer(AtomicReaderContext context, bool scoreDocsInOrder, IBits acceptDocs) diff --git a/src/Lucene.Net.Tests/Search/TestCachingCollector.cs b/src/Lucene.Net.Tests/Search/TestCachingCollector.cs index b3476364d6..22399ff850 100644 --- a/src/Lucene.Net.Tests/Search/TestCachingCollector.cs +++ b/src/Lucene.Net.Tests/Search/TestCachingCollector.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -152,9 +152,7 @@ public virtual void TestIllegalStateOnReplay() cc.Replay(new NoOpCollector(false)); Assert.Fail("replay should fail if CachingCollector is not cached"); } -#pragma warning disable 168 - catch (InvalidOperationException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalStateException()) { // expected } @@ -189,9 +187,7 @@ public virtual void TestIllegalCollectorOnReplay() cc.Replay(new NoOpCollector(false)); // this call should fail Assert.Fail("should have failed if an in-order Collector was given to replay(), " + "while CachingCollector was initialized with out-of-order collection"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // ok } diff --git a/src/Lucene.Net.Tests/Search/TestControlledRealTimeReopenThread.cs b/src/Lucene.Net.Tests/Search/TestControlledRealTimeReopenThread.cs index 01f7d15378..5bd9e463a1 100644 --- a/src/Lucene.Net.Tests/Search/TestControlledRealTimeReopenThread.cs +++ b/src/Lucene.Net.Tests/Search/TestControlledRealTimeReopenThread.cs @@ -465,10 +465,9 @@ public override void Run() writer.DeleteDocuments(new TermQuery(new Term("foo", "barista"))); manager.MaybeRefresh(); // kick off another reopen so we inc. the internal gen } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - Console.WriteLine(e.ToString()); - Console.Write(e.StackTrace); + e.printStackTrace(); } finally { @@ -499,10 +498,10 @@ public override void Run() { thread.WaitForGeneration(lastGen); } - catch (ThreadInterruptedException ie) + catch (Exception ie) when (ie.IsInterruptedException()) { Thread.CurrentThread.Interrupt(); - throw new Exception(ie.Message, ie); + throw RuntimeException.Create(ie); } finished.Value = true; } @@ -555,9 +554,7 @@ public virtual void TestEvilSearcherFactory() new SearcherManager(w.IndexWriter, false, theEvilOne); fail("didn't hit expected exception"); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } @@ -731,9 +728,9 @@ public override void Run() assertTrue(SlowFileExists(dir, name)); } } - 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.Tests/Search/TestDisjunctionMaxQuery.cs b/src/Lucene.Net.Tests/Search/TestDisjunctionMaxQuery.cs index feb6cf6278..77608980a9 100644 --- a/src/Lucene.Net.Tests/Search/TestDisjunctionMaxQuery.cs +++ b/src/Lucene.Net.Tests/Search/TestDisjunctionMaxQuery.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; @@ -245,7 +245,7 @@ public virtual void TestSimpleEqualScores1() Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same"); } } - catch (Exception /*e*/) + catch (Exception e) when (e.IsError()) { PrintHits("testSimpleEqualScores1", h, s); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) @@ -275,7 +275,7 @@ public virtual void TestSimpleEqualScores2() Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same"); } } - catch (Exception /*e*/) + catch (Exception e) when (e.IsError()) { PrintHits("testSimpleEqualScores2", h, s); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) @@ -307,7 +307,7 @@ public virtual void TestSimpleEqualScores3() Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same"); } } - catch (Exception /*e*/) + catch (Exception e) when (e.IsError()) { PrintHits("testSimpleEqualScores3", h, s); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) @@ -338,7 +338,7 @@ public virtual void TestSimpleTiebreaker() Assert.IsTrue(score0 > score1, "d2 does not have better score then others: " + score0 + " >? " + score1); Assert.AreEqual(score1, score2, SCORE_COMP_THRESH, "d4 and d1 don't have equal scores"); } - catch (Exception /*e*/) + catch (Exception e) when (e.IsError()) { PrintHits("testSimpleTiebreaker", h, s); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) @@ -389,7 +389,7 @@ public virtual void TestBooleanRequiredEqualScores() Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same"); } } - catch (Exception /*e*/) + catch (Exception e) when (e.IsError()) { PrintHits("testBooleanRequiredEqualScores1", h, s); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) @@ -432,7 +432,7 @@ public virtual void TestBooleanOptionalNoTiebreaker() float score1 = h[h.Length - 1].Score; Assert.IsTrue(score > score1, "d1 does not have worse score then others: " + score + " >? " + score1); } - catch (Exception /*e*/) + catch (Exception e) when (e.IsError()) { PrintHits("testBooleanOptionalNoTiebreaker", h, s); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) @@ -486,7 +486,7 @@ public virtual void TestBooleanOptionalWithTiebreaker() Assert.AreEqual("d1", doc3, "wrong fourth"); Assert.IsTrue(score2 > score3, "d1 does not have worse score then d3: " + score2 + " >? " + score3); } - catch (Exception /*e*/) + catch (Exception e) when (e.IsError()) { PrintHits("testBooleanOptionalWithTiebreaker", h, s); 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/Search/TestElevationComparator.cs b/src/Lucene.Net.Tests/Search/TestElevationComparator.cs index 848fa97bcd..54d5f859a3 100644 --- a/src/Lucene.Net.Tests/Search/TestElevationComparator.cs +++ b/src/Lucene.Net.Tests/Search/TestElevationComparator.cs @@ -188,7 +188,7 @@ public override void SetBottom(int slot) public override void SetTopValue(object value) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } private int DocVal(int doc) @@ -230,7 +230,7 @@ public override FieldComparer SetNextReader(AtomicReaderContext context) public override int CompareTop(int doc) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } diff --git a/src/Lucene.Net.Tests/Search/TestFieldCache.cs b/src/Lucene.Net.Tests/Search/TestFieldCache.cs index 81a4f6ef1b..239f3e43f7 100644 --- a/src/Lucene.Net.Tests/Search/TestFieldCache.cs +++ b/src/Lucene.Net.Tests/Search/TestFieldCache.cs @@ -588,10 +588,10 @@ public override void Run() } } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { failed.Value = true; - throw new Exception(t.Message, t); + throw RuntimeException.Create(t); } } } @@ -625,9 +625,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetInt32s(ar, "binary", false); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -640,9 +638,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetTermsIndex(ar, "binary"); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -651,9 +647,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetDocTermOrds(ar, "binary"); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -662,9 +656,7 @@ public virtual void TestDocValuesIntegration() new DocTermOrds(ar, null, "binary"); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -677,9 +669,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetInt32s(ar, "sorted", false); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -688,9 +678,7 @@ public virtual void TestDocValuesIntegration() new DocTermOrds(ar, null, "sorted"); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -722,9 +710,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetTerms(ar, "numeric", true); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -733,9 +719,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetTermsIndex(ar, "numeric"); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -744,9 +728,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetDocTermOrds(ar, "numeric"); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -755,9 +737,7 @@ public virtual void TestDocValuesIntegration() new DocTermOrds(ar, null, "numeric"); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -772,9 +752,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetInt32s(ar, "sortedset", false); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -783,9 +761,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetTerms(ar, "sortedset", true); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -794,9 +770,7 @@ public virtual void TestDocValuesIntegration() FieldCache.DEFAULT.GetTermsIndex(ar, "sortedset"); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } @@ -805,9 +779,7 @@ public virtual void TestDocValuesIntegration() new DocTermOrds(ar, null, "sortedset"); Assert.Fail(); } -#pragma warning disable 168 - catch (InvalidOperationException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalStateException()) { } diff --git a/src/Lucene.Net.Tests/Search/TestFilteredQuery.cs b/src/Lucene.Net.Tests/Search/TestFilteredQuery.cs index 9fe12bb70c..8472201033 100644 --- a/src/Lucene.Net.Tests/Search/TestFilteredQuery.cs +++ b/src/Lucene.Net.Tests/Search/TestFilteredQuery.cs @@ -418,9 +418,7 @@ public virtual void TestInvalidArguments() new FilteredQuery(null, null); Assert.Fail("Should throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { // pass } @@ -429,9 +427,7 @@ public virtual void TestInvalidArguments() new FilteredQuery(new TermQuery(new Term("field", "one")), null); Assert.Fail("Should throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { // pass } @@ -440,9 +436,7 @@ public virtual void TestInvalidArguments() new FilteredQuery(null, new PrefixFilter(new Term("field", "o"))); Assert.Fail("Should throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (ArgumentNullException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) { // pass } diff --git a/src/Lucene.Net.Tests/Search/TestFuzzyQuery.cs b/src/Lucene.Net.Tests/Search/TestFuzzyQuery.cs index c9601f1534..989118fa4d 100644 --- a/src/Lucene.Net.Tests/Search/TestFuzzyQuery.cs +++ b/src/Lucene.Net.Tests/Search/TestFuzzyQuery.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using NUnit.Framework; using System; using System.Collections.Generic; @@ -398,9 +398,7 @@ public virtual void TestDistanceAsEditsSearching() q = new FuzzyQuery(new Term("field", "t"), 3); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // expected } diff --git a/src/Lucene.Net.Tests/Search/TestIndexSearcher.cs b/src/Lucene.Net.Tests/Search/TestIndexSearcher.cs index 4c8ab13476..03a3f5ab50 100644 --- a/src/Lucene.Net.Tests/Search/TestIndexSearcher.cs +++ b/src/Lucene.Net.Tests/Search/TestIndexSearcher.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Support.Threading; using Lucene.Net.Util; @@ -138,9 +138,7 @@ public virtual void TestSearchAfterPassedMaxDoc() s.SearchAfter(new ScoreDoc(r.MaxDoc, 0.54f), new MatchAllDocsQuery(), 10); Assert.Fail("should have hit IllegalArgumentException when searchAfter exceeds maxDoc"); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // ok } diff --git a/src/Lucene.Net.Tests/Search/TestLiveFieldValues.cs b/src/Lucene.Net.Tests/Search/TestLiveFieldValues.cs index 081ef86540..6c36474486 100644 --- a/src/Lucene.Net.Tests/Search/TestLiveFieldValues.cs +++ b/src/Lucene.Net.Tests/Search/TestLiveFieldValues.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index; using NUnit.Framework; @@ -236,9 +236,9 @@ public override void Run() } } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { - throw new Exception(t.Message, t); + throw RuntimeException.Create(t); } } } diff --git a/src/Lucene.Net.Tests/Search/TestMultiPhraseQuery.cs b/src/Lucene.Net.Tests/Search/TestMultiPhraseQuery.cs index 70bc1e8f56..4600a4f056 100644 --- a/src/Lucene.Net.Tests/Search/TestMultiPhraseQuery.cs +++ b/src/Lucene.Net.Tests/Search/TestMultiPhraseQuery.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using Lucene.Net.Documents; using NUnit.Framework; using System; @@ -148,9 +148,7 @@ public virtual void TestPhrasePrefix() query4.Add(new Term("field2", "foobar")); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { // okay, all terms must belong to the same field } @@ -658,9 +656,7 @@ public virtual void TestNegativeSlop() query.Slop = -2; Assert.Fail("didn't get expected exception"); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // expected exception } diff --git a/src/Lucene.Net.Tests/Search/TestMultiThreadTermVectors.cs b/src/Lucene.Net.Tests/Search/TestMultiThreadTermVectors.cs index 734490a1ed..ea4be552f5 100644 --- a/src/Lucene.Net.Tests/Search/TestMultiThreadTermVectors.cs +++ b/src/Lucene.Net.Tests/Search/TestMultiThreadTermVectors.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; @@ -87,7 +87,7 @@ public virtual void Test() TestTermPositionVectors(reader, i); } } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { Assert.Fail(ioe.Message); } @@ -101,7 +101,7 @@ public virtual void Test() /// close the opened reader reader.Dispose(); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { Console.WriteLine(ioe.ToString()); Console.Write(ioe.StackTrace); @@ -188,10 +188,9 @@ public void Run() TestTermVectors(); } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - Console.WriteLine(e.ToString()); - Console.Write(e.StackTrace); + e.printStackTrace(); } return; } diff --git a/src/Lucene.Net.Tests/Search/TestPhraseQuery.cs b/src/Lucene.Net.Tests/Search/TestPhraseQuery.cs index 9a4b9f93f4..10cddc89e9 100644 --- a/src/Lucene.Net.Tests/Search/TestPhraseQuery.cs +++ b/src/Lucene.Net.Tests/Search/TestPhraseQuery.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Analysis; +using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Documents; using Lucene.Net.Index; @@ -788,7 +788,7 @@ public virtual void TestRandomPhrases() break; } } - IOException priorException = null; + Exception priorException = null; // LUCENENET: No need to cast to IOExcpetion TokenStream ts = analyzer.GetTokenStream("ignore", new StringReader(term)); try { @@ -802,7 +802,7 @@ public virtual void TestRandomPhrases() } ts.End(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { priorException = e; } @@ -880,9 +880,7 @@ public virtual void TestNegativeSlop() query.Slop = -2; Assert.Fail("didn't get expected exception"); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (ArgumentOutOfRangeException) // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) { // expected exception } diff --git a/src/Lucene.Net.Tests/Search/TestQueryRescorer.cs b/src/Lucene.Net.Tests/Search/TestQueryRescorer.cs index a23ff7ea2a..7e27afee63 100644 --- a/src/Lucene.Net.Tests/Search/TestQueryRescorer.cs +++ b/src/Lucene.Net.Tests/Search/TestQueryRescorer.cs @@ -397,24 +397,31 @@ public virtual void TestRandom() Array.Sort(expected, Comparer.Create((a, b) => { - int av = idToNum[Convert.ToInt32(r.Document(a).Get("id"))]; - int bv = idToNum[Convert.ToInt32(r.Document(b).Get("id"))]; - if (av < bv) + try { - return -reverseInt; - } - else if (bv < av) - { - return reverseInt; + int av = idToNum[Convert.ToInt32(r.Document(a).Get("id"))]; + int bv = idToNum[Convert.ToInt32(r.Document(b).Get("id"))]; + if (av < bv) + { + return -reverseInt; + } + else if (bv < av) + { + return reverseInt; + } + else + { + // Tie break by docID, ascending + return a - b; + } } - else + catch (Exception ioe) when (ioe.IsIOException()) { - // Tie break by docID, ascending - return a - b; + throw RuntimeException.Create(ioe); } }) ); - + bool fail = false; for (int i = 0; i < numHits; i++) { diff --git a/src/Lucene.Net.Tests/Search/TestSameScoresWithThreads.cs b/src/Lucene.Net.Tests/Search/TestSameScoresWithThreads.cs index d309226297..0ebf44cf52 100644 --- a/src/Lucene.Net.Tests/Search/TestSameScoresWithThreads.cs +++ b/src/Lucene.Net.Tests/Search/TestSameScoresWithThreads.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using J2N.Threading; using NUnit.Framework; using System; @@ -153,9 +153,9 @@ public override void Run() } } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - throw new Exception(e.Message, e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net.Tests/Search/TestScorerPerf.cs b/src/Lucene.Net.Tests/Search/TestScorerPerf.cs index bf2fba79c4..f4184a0a88 100644 --- a/src/Lucene.Net.Tests/Search/TestScorerPerf.cs +++ b/src/Lucene.Net.Tests/Search/TestScorerPerf.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Support; using NUnit.Framework; @@ -157,7 +157,7 @@ public virtual void Collect(int doc, float score) pos = answer.NextSetBit(pos + 1); if (pos != doc + docBase) { - throw new Exception("Expected doc " + pos + " but got " + doc + docBase); + throw RuntimeException.Create("Expected doc " + pos + " but got " + doc + docBase); } base.Collect(doc); } diff --git a/src/Lucene.Net.Tests/Search/TestSearchWithThreads.cs b/src/Lucene.Net.Tests/Search/TestSearchWithThreads.cs index 7cdddaf7f9..3639461a36 100644 --- a/src/Lucene.Net.Tests/Search/TestSearchWithThreads.cs +++ b/src/Lucene.Net.Tests/Search/TestSearchWithThreads.cs @@ -158,10 +158,10 @@ public override void Run() Assert.IsTrue(totSearch > 0 && totHits > 0); netSearch.AddAndGet(totSearch); } - catch (Exception exc) + catch (Exception exc) when (exc.IsException()) { failed.Value = (true); - throw new Exception(exc.Message, exc); + throw RuntimeException.Create(exc); } } } diff --git a/src/Lucene.Net.Tests/Search/TestSearcherManager.cs b/src/Lucene.Net.Tests/Search/TestSearcherManager.cs index 246c10ac4b..11f2990384 100644 --- a/src/Lucene.Net.Tests/Search/TestSearcherManager.cs +++ b/src/Lucene.Net.Tests/Search/TestSearcherManager.cs @@ -166,7 +166,7 @@ public override void Run() } } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (Verbose) { @@ -174,7 +174,7 @@ public override void Run() Console.Out.Write(t.StackTrace); } outerInstance.m_failed.Value = (true); - throw new Exception(t.ToString(), t); + throw RuntimeException.Create(t); } } } @@ -303,9 +303,7 @@ public virtual void TestIntermediateClose() searcherManager.Acquire(); fail("already closed"); } -#pragma warning disable 168 - catch (ObjectDisposedException ex) -#pragma warning restore 168 + catch (Exception ex) when (ex.IsAlreadyClosedException()) { // expected } @@ -349,7 +347,7 @@ public override IndexSearcher NewSearcher(IndexReader r) awaitClose.Wait(); } } - catch (ThreadInterruptedException) + catch (Exception e) when (e.IsInterruptedException()) { // } @@ -387,11 +385,11 @@ public void Run() searcherManager.MaybeRefresh(); success.Value = (true); } - catch (ObjectDisposedException) + catch (Exception e) when (e.IsAlreadyClosedException()) { // expected } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { if (Verbose) { @@ -438,7 +436,15 @@ public virtual void TestReferenceDecrementIllegally() acquire.IndexReader.DecRef(); sm.Release(acquire); - Assert.Throws(() => sm.Acquire(), "acquire should have thrown an InvalidOperationException since we modified the refCount outside of the manager"); + try + { + sm.Acquire(); + fail("acquire should have thrown an InvalidOperationException since we modified the refCount outside of the manager"); + } + catch (Exception ise) when (ise.IsIllegalStateException()) + { + // expected + } // sm.Dispose(); -- already closed writer.Dispose(); @@ -462,9 +468,7 @@ public virtual void TestEnsureOpen() // this should fail sm.Acquire(); } -#pragma warning disable 168 - catch (ObjectDisposedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsAlreadyClosedException()) { // ok } @@ -474,9 +478,7 @@ public virtual void TestEnsureOpen() // this should fail sm.MaybeRefresh(); } -#pragma warning disable 168 - catch (ObjectDisposedException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsAlreadyClosedException()) { // ok } @@ -546,9 +548,7 @@ public virtual void TestEvilSearcherFactory() { new SearcherManager(dir, theEvilOne); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } @@ -556,9 +556,7 @@ public virtual void TestEvilSearcherFactory() { new SearcherManager(w.IndexWriter, random.NextBoolean(), theEvilOne); } -#pragma warning disable 168 - catch (InvalidOperationException ise) -#pragma warning restore 168 + catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } @@ -634,9 +632,9 @@ public override void Run() // this used to not release the lock, preventing other threads from obtaining it. sm.MaybeRefreshBlocking(); } - 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.Tests/Search/TestSortRescorer.cs b/src/Lucene.Net.Tests/Search/TestSortRescorer.cs index bec82e7664..981d37a700 100644 --- a/src/Lucene.Net.Tests/Search/TestSortRescorer.cs +++ b/src/Lucene.Net.Tests/Search/TestSortRescorer.cs @@ -170,20 +170,27 @@ public virtual void TestRandom() Array.Sort(expected, Comparer.Create((a, b) => { - int av = idToNum[Convert.ToInt32(r.Document(a).Get("id"))]; - int bv = idToNum[Convert.ToInt32(r.Document(b).Get("id"))]; - if (av < bv) + try { - return -reverseInt; + int av = idToNum[Convert.ToInt32(r.Document(a).Get("id"))]; + int bv = idToNum[Convert.ToInt32(r.Document(b).Get("id"))]; + if (av < bv) + { + return -reverseInt; + } + else if (bv < av) + { + return reverseInt; + } + else + { + // Tie break by docID, ascending + return a - b; + } } - else if (bv < av) + catch (Exception ioe) when (ioe.IsIOException()) { - return reverseInt; - } - else - { - // Tie break by docID, ascending - return a - b; + throw RuntimeException.Create(ioe); } })); diff --git a/src/Lucene.Net.Tests/Search/TestTimeLimitingCollector.cs b/src/Lucene.Net.Tests/Search/TestTimeLimitingCollector.cs index e3cf33f300..d35dc022ca 100644 --- a/src/Lucene.Net.Tests/Search/TestTimeLimitingCollector.cs +++ b/src/Lucene.Net.Tests/Search/TestTimeLimitingCollector.cs @@ -155,7 +155,7 @@ private void DoTestSearch() Search(tlCollector); totalTLCResults = myHc.HitCount(); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { e.printStackTrace(); assertTrue("Unexpected exception: " + e, false); //==fail @@ -205,7 +205,7 @@ private void DoTestTimeout(bool multiThreaded, bool greedy) { timoutException = x; } - catch (Exception e) + catch (Exception e) when (e.IsException()) { assertTrue("Unexpected exception: " + e, false); //==fail } diff --git a/src/Lucene.Net.Tests/Store/TestBufferedIndexInput.cs b/src/Lucene.Net.Tests/Store/TestBufferedIndexInput.cs index 188ad4b88c..c54bb2c0ee 100644 --- a/src/Lucene.Net.Tests/Store/TestBufferedIndexInput.cs +++ b/src/Lucene.Net.Tests/Store/TestBufferedIndexInput.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Documents; +using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; @@ -178,9 +178,7 @@ public virtual void TestEOF() CheckReadBytes(input, 11, pos); Assert.Fail("Block read past end of file"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { /* success */ } @@ -190,9 +188,7 @@ public virtual void TestEOF() CheckReadBytes(input, 50, pos); Assert.Fail("Block read past end of file"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { /* success */ } @@ -202,9 +198,7 @@ public virtual void TestEOF() CheckReadBytes(input, 100000, pos); Assert.Fail("Block read past end of file"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { /* success */ } diff --git a/src/Lucene.Net.Tests/Store/TestCopyBytes.cs b/src/Lucene.Net.Tests/Store/TestCopyBytes.cs index 595c24076d..dd7b93b3d4 100644 --- a/src/Lucene.Net.Tests/Store/TestCopyBytes.cs +++ b/src/Lucene.Net.Tests/Store/TestCopyBytes.cs @@ -192,9 +192,9 @@ public override void Run() dst.CopyBytes(src, src.Length - 100); dst.Dispose(); } - 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.Tests/Store/TestDirectory.cs b/src/Lucene.Net.Tests/Store/TestDirectory.cs index 53b94e4351..7eb1eb9f74 100644 --- a/src/Lucene.Net.Tests/Store/TestDirectory.cs +++ b/src/Lucene.Net.Tests/Store/TestDirectory.cs @@ -50,9 +50,7 @@ public virtual void TestDetectClose() dir.CreateOutput("test", NewIOContext(Random)); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (ObjectDisposedException ace) -#pragma warning restore 168 + catch (Exception ace) when (ace.IsAlreadyClosedException()) { } } @@ -110,9 +108,9 @@ public override void Run() using (IndexOutput output = outerBDWrapper.CreateOutput(fileName, NewIOContext(Random))) { } Assert.IsTrue(SlowFileExists(outerBDWrapper, fileName)); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } @@ -138,25 +136,21 @@ public override void Run() string[] files = outerBDWrapper.ListAll(); foreach (string file in files) { + //System.out.println("file:" + file); try { using IndexInput input = outerBDWrapper.OpenInput(file, NewIOContext(Random)); } -#pragma warning disable 168 - catch (FileNotFoundException fne) -#pragma warning restore 168 - { - } - // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException - // in Lucene, we need to catch it here to be on the safe side. - catch (DirectoryNotFoundException) + catch (Exception fne) when (fne.IsNoSuchFileExceptionOrFileNotFoundException()) { + // ignore } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { + // ignore if (!e.Message.Contains("still open for writing")) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } if (Random.NextBoolean()) @@ -165,9 +159,9 @@ public override void Run() } } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } @@ -362,9 +356,7 @@ public virtual void TestNotDirectory() var d = new SimpleFSDirectory(new DirectoryInfo(Path.Combine(path.FullName, "afile")), null); Assert.Fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (DirectoryNotFoundException nsde) -#pragma warning restore 168 + catch (Exception nsde) when (nsde.IsNoSuchDirectoryException()) { // Expected } @@ -412,13 +404,7 @@ public virtual void TestFsyncDoesntCreateNewFiles() // Assert.Fail("didn't get expected exception, instead fsync created new files: " + // Collections.ToString(fsdir.ListAll())); //} - //catch (FileNotFoundException) - //{ - // // ok - //} - //// LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException - //// in Lucene, we need to catch it here to be on the safe side. - //catch (DirectoryNotFoundException) + //catch (Exception expected) when (expected.IsNoSuchFileExceptionOrFileNotFoundException()) //{ // // ok //} diff --git a/src/Lucene.Net.Tests/Store/TestFileSwitchDirectory.cs b/src/Lucene.Net.Tests/Store/TestFileSwitchDirectory.cs index 903c44ac05..a4438d7e81 100644 --- a/src/Lucene.Net.Tests/Store/TestFileSwitchDirectory.cs +++ b/src/Lucene.Net.Tests/Store/TestFileSwitchDirectory.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Index.Extensions; +using Lucene.Net.Index.Extensions; using Lucene.Net.Support; using NUnit.Framework; using System; @@ -120,7 +120,7 @@ public virtual void TestNoDir() DirectoryReader.Open(dir); Assert.Fail("did not hit expected exception"); } - catch (DirectoryNotFoundException) + catch (Exception nsde) when (nsde.IsNoSuchDirectoryException()) { // expected } diff --git a/src/Lucene.Net.Tests/Store/TestLock.cs b/src/Lucene.Net.Tests/Store/TestLock.cs index 74e26e8deb..d00075fd1b 100644 --- a/src/Lucene.Net.Tests/Store/TestLock.cs +++ b/src/Lucene.Net.Tests/Store/TestLock.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using NUnit.Framework; +using System; using System.IO; using Assert = Lucene.Net.TestFramework.Assert; @@ -37,9 +38,7 @@ public virtual void TestObtain() @lock.Obtain(Lock.LOCK_POLL_INTERVAL); Assert.Fail("Should have failed to obtain lock"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { Assert.AreEqual(@lock.LockAttempts, 2, "should attempt to lock more than once"); } diff --git a/src/Lucene.Net.Tests/Store/TestLockFactory.cs b/src/Lucene.Net.Tests/Store/TestLockFactory.cs index b8018b6213..e3e0e22026 100644 --- a/src/Lucene.Net.Tests/Store/TestLockFactory.cs +++ b/src/Lucene.Net.Tests/Store/TestLockFactory.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; @@ -98,9 +98,9 @@ public virtual void TestRAMDirectoryNoLocking() { writer2 = new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.APPEND)); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - Console.Out.Write(e.StackTrace); + e.printStackTrace(); Assert.Fail("Should not have hit an IOException with no locking"); } @@ -129,9 +129,7 @@ public virtual void TestDefaultRAMDirectory() writer2 = new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.APPEND)); Assert.Fail("Should have hit an IOException with two IndexWriters on default SingleInstanceLockFactory"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { } @@ -313,7 +311,7 @@ public override void Run() { writer = new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.APPEND)); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (e.ToString().IndexOf(" timed out:", StringComparison.Ordinal) == -1) { @@ -331,11 +329,11 @@ public override void Run() // FIFO). } } - catch (Exception e) + catch (Exception e) when (e.IsException()) { HitException = true; Console.WriteLine("Stress Test Index Writer: creation hit unexpected exception: " + e.ToString()); - Console.Out.Write(e.StackTrace); + e.printStackTrace(Console.Out); break; } if (writer != null) @@ -344,7 +342,7 @@ public override void Run() { outerInstance.AddDoc(writer); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { HitException = true; Console.WriteLine("Stress Test Index Writer: addDoc hit unexpected exception: " + e.ToString()); @@ -355,7 +353,7 @@ public override void Run() { writer.Dispose(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { HitException = true; Console.WriteLine("Stress Test Index Writer: close hit unexpected exception: " + e.ToString()); @@ -399,18 +397,18 @@ public override void Run() #endif reader); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { HitException = true; Console.WriteLine("Stress Test Index Searcher: create hit unexpected exception: " + e.ToString()); - Console.Out.Write(e.StackTrace); + e.printStackTrace(Console.Out); break; } try { searcher.Search(query, null, 1000); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { HitException = true; Console.WriteLine("Stress Test Index Searcher: search hit unexpected exception: " + e.ToString()); @@ -422,7 +420,7 @@ public override void Run() { reader.Dispose(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { HitException = true; Console.WriteLine("Stress Test Index Searcher: close hit unexpected exception: " + e.ToString()); diff --git a/src/Lucene.Net.Tests/Store/TestMockDirectoryWrapper.cs b/src/Lucene.Net.Tests/Store/TestMockDirectoryWrapper.cs index 14c610d446..7735dc40f5 100644 --- a/src/Lucene.Net.Tests/Store/TestMockDirectoryWrapper.cs +++ b/src/Lucene.Net.Tests/Store/TestMockDirectoryWrapper.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using System.IO; using Assert = Lucene.Net.TestFramework.Assert; @@ -39,7 +39,7 @@ public virtual void TestFailIfIndexWriterNotClosed() dir.Dispose(); Assert.Fail(); } - catch (Exception expected) + catch (Exception expected) when (expected.IsException()) { Assert.IsTrue(expected.Message.Contains("there are still open locks")); } @@ -58,7 +58,7 @@ public virtual void TestFailIfIndexWriterNotClosedChangeLockFactory() dir.Dispose(); Assert.Fail(); } - catch (Exception expected) + catch (Exception expected) when (expected.IsException()) { Assert.IsTrue(expected.Message.Contains("there are still open locks")); } @@ -83,9 +83,7 @@ public void TestDiskFull() @out.WriteBytes(bytes, bytes.Length); Assert.Fail("should have failed on disk full"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // expected } @@ -105,9 +103,7 @@ public void TestDiskFull() @out.CopyBytes(new ByteArrayDataInput(bytes), bytes.Length); Assert.Fail("should have failed on disk full"); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // expected } diff --git a/src/Lucene.Net.Tests/Store/TestMultiMMap.cs b/src/Lucene.Net.Tests/Store/TestMultiMMap.cs index e6228ef621..0318c1f148 100644 --- a/src/Lucene.Net.Tests/Store/TestMultiMMap.cs +++ b/src/Lucene.Net.Tests/Store/TestMultiMMap.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Attributes; +using Lucene.Net.Attributes; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; @@ -77,9 +77,7 @@ public virtual void TestCloneSafety() one.ReadVInt32(); Assert.Fail("Must throw ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ignore) -#pragma warning restore 168 + catch (Exception ignore) when (ignore.IsAlreadyClosedException()) { // pass } @@ -88,9 +86,7 @@ public virtual void TestCloneSafety() two.ReadVInt32(); Assert.Fail("Must throw ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ignore) -#pragma warning restore 168 + catch (Exception ignore) when (ignore.IsAlreadyClosedException()) { // pass } @@ -99,9 +95,7 @@ public virtual void TestCloneSafety() three.ReadVInt32(); Assert.Fail("Must throw ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ignore) -#pragma warning restore 168 + catch (Exception ignore) when (ignore.IsAlreadyClosedException()) { // pass } @@ -129,9 +123,7 @@ public virtual void TestCloneClose() two.ReadVInt32(); Assert.Fail("Must throw ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ignore) -#pragma warning restore 168 + catch (Exception ignore) when (ignore.IsAlreadyClosedException()) { // pass } @@ -160,9 +152,7 @@ public virtual void TestCloneSliceSafety() one.ReadInt32(); Assert.Fail("Must throw ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ignore) -#pragma warning restore 168 + catch (Exception ignore) when (ignore.IsAlreadyClosedException()) { // pass } @@ -171,9 +161,7 @@ public virtual void TestCloneSliceSafety() two.ReadInt32(); Assert.Fail("Must throw ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ignore) -#pragma warning restore 168 + catch (Exception ignore) when (ignore.IsAlreadyClosedException()) { // pass } @@ -182,9 +170,7 @@ public virtual void TestCloneSliceSafety() three.ReadInt32(); Assert.Fail("Must throw ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ignore) -#pragma warning restore 168 + catch (Exception ignore) when (ignore.IsAlreadyClosedException()) { // pass } @@ -193,9 +179,7 @@ public virtual void TestCloneSliceSafety() four.ReadInt32(); Assert.Fail("Must throw ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ignore) -#pragma warning restore 168 + catch (Exception ignore) when (ignore.IsAlreadyClosedException()) { // pass } @@ -225,9 +209,7 @@ public virtual void TestCloneSliceClose() one.ReadInt32(); Assert.Fail("Must throw ObjectDisposedException"); } -#pragma warning disable 168 - catch (ObjectDisposedException ignore) -#pragma warning restore 168 + catch (Exception ignore) when (ignore.IsAlreadyClosedException()) { // pass } diff --git a/src/Lucene.Net.Tests/Store/TestNRTCachingDirectory.cs b/src/Lucene.Net.Tests/Store/TestNRTCachingDirectory.cs index 113f490f0d..0cf31ed1d7 100644 --- a/src/Lucene.Net.Tests/Store/TestNRTCachingDirectory.cs +++ b/src/Lucene.Net.Tests/Store/TestNRTCachingDirectory.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; @@ -151,7 +151,7 @@ public virtual void TestNoDir() DirectoryReader.Open(dir); Assert.Fail("did not hit expected exception"); } - catch (DirectoryNotFoundException) + catch (Exception nsde) when (nsde.IsNoSuchDirectoryException()) { // expected } diff --git a/src/Lucene.Net.Tests/Store/TestRAMDirectory.cs b/src/Lucene.Net.Tests/Store/TestRAMDirectory.cs index 76970da7f9..74f4f659cc 100644 --- a/src/Lucene.Net.Tests/Store/TestRAMDirectory.cs +++ b/src/Lucene.Net.Tests/Store/TestRAMDirectory.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; @@ -165,9 +165,9 @@ public override void Run() { writer.AddDocument(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.Tests/Support/ExceptionHandling/TestExceptionExtensions.cs b/src/Lucene.Net.Tests/Support/ExceptionHandling/TestExceptionExtensions.cs new file mode 100644 index 0000000000..f7f0213fa7 --- /dev/null +++ b/src/Lucene.Net.Tests/Support/ExceptionHandling/TestExceptionExtensions.cs @@ -0,0 +1,1058 @@ +using J2N.Text; +using Lucene.Net.Attributes; +using Lucene.Net.Index; +using Lucene.Net.Queries.Function.DocValues; +using Lucene.Net.Search; +using Lucene.Net.Util; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Resources; +using System.Security; +using System.Threading; +using Assert = Lucene.Net.TestFramework.Assert; +using JCG = J2N.Collections.Generic; + +namespace Lucene +{ + /* + * 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. + */ + +#pragma warning disable IDE0001 // Name can be simplified + [LuceneNetSpecific] + public class TestExceptionExtensions : LuceneTestCase + { + // Internal types references + private static readonly Type 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 + + private static readonly Type MetadataExceptionType = + // .NET Core/5.0 + Type.GetType("System.Reflection.MetadataException, System.Private.CoreLib") ?? + // .NET Framework + Type.GetType("System.Reflection.MetadataException, mscorlib"); + + private static readonly Type CrossAppDomainMarshaledExceptionType = + // .NET Core 2.1 Only + Type.GetType("System.CrossAppDomainMarshaledException, System.Private.CoreLib"); + + private static readonly Type SwitchExpressionExceptionType = + // No .NET Framework or .NET Core 2.x support + // .NET Core 3.1 + Type.GetType("System.Runtime.CompilerServices.SwitchExpressionException, System.Runtime.Extensions") ?? + // .NET 5 + Type.GetType("System.Runtime.CompilerServices.SwitchExpressionException, System.Private.CoreLib"); + + private static readonly Type RemotingExceptionType = + // .NET Framework only + Type.GetType("System.Runtime.Remoting.RemotingException, mscorlib"); + + private static readonly Type RemotingTimeoutExceptionType = + // .NET Framework only + Type.GetType("System.Runtime.Remoting.RemotingTimeoutException, mscorlib"); + + private static readonly Type RemotingServerExceptionType = + // .NET Framework only + Type.GetType("System.Runtime.Remoting.ServerException, mscorlib"); + + private static readonly Type CryptographicUnexpectedOperationExceptionType = + // .NET Framework only + Type.GetType("System.Security.Cryptography.CryptographicUnexpectedOperationException, mscorlib"); + + private static readonly Type HostProtectionExceptionType = + // .NET Framework only + Type.GetType("System.Security.HostProtectionException, mscorlib"); + + private static readonly Type PolicyExceptionType = + // .NET Framework only + Type.GetType("System.Security.Policy.PolicyException, mscorlib"); + + private static readonly Type IdentityNotMappedExceptionType = + // .NET Framework only + Type.GetType("System.Security.Principal.IdentityNotMappedException, mscorlib"); + + private static readonly Type XmlSyntaxExceptionType = + // .NET Framework only + Type.GetType("System.Security.XmlSyntaxException, mscorlib"); + + private static readonly Type PrivilegeNotHeldExceptionType = + // .NET Framework only + Type.GetType("System.Security.AccessControl.PrivilegeNotHeldException, mscorlib"); + + private static readonly Type NUnitFrameworkInternalInvalidPlatformExceptionType = + Type.GetType("NUnit.Framework.Internal.InvalidPlatformException, NUnit.Framework"); + + + // Load exception types from all assemblies + private static readonly Assembly[] LuceneAssemblies = new Assembly[] + { + typeof(Lucene.Net.Analysis.Analyzer).Assembly, // Lucene.Net + typeof(Lucene.Net.Analysis.Standard.ClassicAnalyzer).Assembly, // Lucene.Net.Analysis.Common + typeof(Lucene.Net.Analysis.Ja.GraphvizFormatter).Assembly, // Lucene.Net.Analysis.Kuromoji + typeof(Lucene.Net.Analysis.Morfologik.MorfologikAnalyzer).Assembly, // Lucene.Net.Analysis.Morfologik +#if FEATURE_OPENNLP + typeof(Lucene.Net.Analysis.OpenNlp.OpenNLPTokenizer).Assembly, // Lucene.Net.Analysis.OpenNlp +#endif + typeof(Lucene.Net.Analysis.Phonetic.BeiderMorseFilter).Assembly, // Lucene.Net.Analysis.Phonetic + typeof(Lucene.Net.Analysis.Cn.Smart.AnalyzerProfile).Assembly, // Lucene.Net.Analysis.SmartCn + typeof(Lucene.Net.Analysis.Stempel.StempelFilter).Assembly, // Lucene.Net.Analysis.Stempel + typeof(Lucene.Net.Benchmarks.Constants).Assembly, // Lucene.Net.Benchmark + typeof(Lucene.Net.Classification.KNearestNeighborClassifier).Assembly, // Lucene.Net.Classification + typeof(Lucene.Net.Codecs.BlockTerms.BlockTermsReader).Assembly, // Lucene.Net.Codecs + typeof(Lucene.Net.Expressions.Bindings).Assembly, // Lucene.Net.Expressions + typeof(Lucene.Net.Facet.Facets).Assembly, // Lucene.Net.Facet + typeof(Lucene.Net.Search.Grouping.ICollectedSearchGroup).Assembly, // Lucene.Net.Grouping + typeof(Lucene.Net.Search.Highlight.DefaultEncoder).Assembly, // Lucene.Net.Highlighter + typeof(Lucene.Net.Join.JoinUtil).Assembly, // Lucene.Net.Join + typeof(Lucene.Net.Index.Memory.MemoryIndex).Assembly, // Lucene.Net.Memory + typeof(Lucene.Net.Misc.SweetSpotSimilarity).Assembly, // Lucene.Net.Misc + typeof(Lucene.Net.Queries.BooleanFilter).Assembly, // Lucene.Net.Queries + typeof(Lucene.Net.QueryParsers.Classic.QueryParser).Assembly, // Lucene.Net.QueryParser + typeof(Lucene.Net.Replicator.IReplicator).Assembly, // Lucene.Net.Replicator + typeof(Lucene.Net.Sandbox.Queries.DuplicateFilter).Assembly, // Lucene.Net.Sandbox + typeof(Lucene.Net.Spatial.DisjointSpatialFilter).Assembly, // Lucene.Net.Spatial + typeof(Lucene.Net.Util.LuceneTestCase).Assembly, // Lucene.Net.TestFramework + }; + + + private static readonly Assembly[] DotNetAssemblies = new Assembly[] + { + typeof(Exception).Assembly + }; + + private static readonly Assembly[] NUnitAssemblies = new Assembly[] + { + typeof(NUnit.Framework.AssertionException).Assembly + }; + + // Base class Exception + private static readonly ICollection DotNetExceptionTypes = LoadTypesSubclassing(baseClass: typeof(Exception), DotNetAssemblies); + private static readonly ICollection NUnitExceptionTypes = LoadTypesSubclassing(baseClass: typeof(Exception), NUnitAssemblies); + private static readonly ICollection LuceneExceptionTypes = LoadTypesSubclassing(baseClass: typeof(Exception), LuceneAssemblies); + + private static readonly ICollection AllExceptionTypes = DotNetExceptionTypes.Union(NUnitExceptionTypes).Union(LuceneExceptionTypes).ToList(); + + // Base class IOException + private static readonly ICollection DotNetIOExceptionTypes = LoadTypesSubclassing(baseClass: typeof(IOException), DotNetAssemblies); + private static readonly ICollection NUnitIOExceptionTypes = LoadTypesSubclassing(baseClass: typeof(IOException), NUnitAssemblies); + private static readonly ICollection LuceneIOExceptionTypes = LoadTypesSubclassing(baseClass: typeof(IOException), LuceneAssemblies); + + private static readonly ICollection AllIOExceptionTypes = DotNetIOExceptionTypes.Union(NUnitIOExceptionTypes).Union(LuceneIOExceptionTypes).ToList(); + + #region Known types of exception families + + private static readonly IEnumerable KnownAssertionErrorTypes = LoadKnownAssertionErrorTypes(); + + private static IEnumerable LoadKnownAssertionErrorTypes() + { + var result = new HashSet + { + typeof(NUnit.Framework.AssertionException), // Corresponds to Java's AssertionError + typeof(NUnit.Framework.MultipleAssertException), // Corresponds to Java's AssertionError + typeof(Lucene.Net.Diagnostics.AssertionException), // Corresponds to Java's AssertionError + + // Types for use as Java Aliases in .NET + typeof(Lucene.AssertionError), + }; + + // Special case - this doesn't exist on .NET Framework, so we only add it if not null + if (!(DebugAssertExceptionType is null)) + { + result.Add(DebugAssertExceptionType); // Corresponds to Java's AssertionError + } + return result; + } + + private static readonly IEnumerable KnownErrorExceptionTypes = LoadKnownErrorExceptionTypes(); + + private static IEnumerable LoadKnownErrorExceptionTypes() + { + return new HashSet(KnownAssertionErrorTypes) // Include all known types that correspond to Java's AssertionError + { + typeof(NUnit.Framework.IgnoreException), // Don't care - only used for testing and we shouldn't catch it in general + typeof(OutOfMemoryException), // Corresponds to Java's OutOfMemoryError + typeof(StackOverflowException), // Corresponds to Java's StackOverflowError + typeof(InsufficientMemoryException), // OutOfMemoryException is the base class + + // Types for use as Java Aliases in .NET + typeof(Lucene.Error), +#pragma warning disable CS0618 // Type or member is obsolete + typeof(Lucene.StackOverflowError), +#pragma warning restore CS0618 // Type or member is obsolete + typeof(Lucene.OutOfMemoryError), + typeof(Lucene.NoClassDefFoundError), + typeof(Lucene.ServiceConfigurationError), + + typeof(Lucene.Net.QueryParsers.Classic.TokenMgrError), + typeof(Lucene.Net.QueryParsers.Flexible.Core.QueryNodeError), + typeof(Lucene.Net.QueryParsers.Flexible.Standard.Parser.TokenMgrError), + typeof(Lucene.Net.QueryParsers.Surround.Parser.TokenMgrError), + + typeof(NUnit.Framework.SuccessException), // Not sure about this, but it seems reasonable to ignore it in most cases because it is NUnit result state + }; + } + + private static readonly IEnumerable KnownExceptionTypes = AllExceptionTypes + // Exceptions in Java exclude Errors + .Except(KnownErrorExceptionTypes) + // Special Case: We never want to catch this NUnit exception + .Where(t => !Type.Equals(t, NUnitFrameworkInternalInvalidPlatformExceptionType)); + + private static readonly IEnumerable KnownThrowableExceptionTypes = AllExceptionTypes + // Special Case: We never want to catch this NUnit exception + .Where(t => !Type.Equals(t, NUnitFrameworkInternalInvalidPlatformExceptionType)); + + + private static readonly IEnumerable KnownIOExceptionTypes = new Type[] { + typeof(UnauthorizedAccessException), + typeof(ObjectDisposedException), + typeof(Lucene.AlreadyClosedException), + }.Union(AllIOExceptionTypes) + // .NET Framework only - Subclasses UnauthorizedAccessException + .Union(new[] { PrivilegeNotHeldExceptionType }); + + private static readonly IEnumerable KnownIndexOutOfBoundsExceptionTypes = new Type[] { + typeof(ArgumentOutOfRangeException), + typeof(IndexOutOfRangeException), + + // Types for use as Java Aliases in .NET + typeof(ArrayIndexOutOfBoundsException), + typeof(StringIndexOutOfBoundsException), + typeof(IndexOutOfBoundsException), + }; + + private static readonly IEnumerable KnownNullPointerExceptionTypes = new Type[] { + typeof(ArgumentNullException), + typeof(NullReferenceException), + + // Types for use as Java Aliases in .NET + typeof(NullPointerException), + }; + + private static readonly IEnumerable KnownIllegalArgumentExceptionTypes = new Type[] { + typeof(ArgumentException), + typeof(ArgumentNullException), + typeof(ArgumentOutOfRangeException), + + // Types for use as Java Aliases in .NET + typeof(Lucene.IllegalArgumentException), + typeof(Lucene.ArrayIndexOutOfBoundsException), + typeof(Lucene.IndexOutOfBoundsException), + typeof(Lucene.NullPointerException), // ArgumentNullException subclass + typeof(Lucene.StringIndexOutOfBoundsException), + + // Subclasses + typeof(System.DuplicateWaitObjectException), + typeof(System.Globalization.CultureNotFoundException), + typeof(System.Text.DecoderFallbackException), + typeof(System.Text.EncoderFallbackException), + }; + + private static readonly IEnumerable KnownIllegalArgumentExceptionTypes_TestEnvironment = new Type[] { + typeof(ArgumentException), + + // Types for use as Java Aliases in .NET + typeof(IllegalArgumentException), + + // Subclasses + typeof(System.DuplicateWaitObjectException), + typeof(System.Globalization.CultureNotFoundException), + typeof(System.Text.DecoderFallbackException), + typeof(System.Text.EncoderFallbackException), + }; + + private static readonly IEnumerable KnownRuntimeExceptionTypes = LoadKnownRuntimeExceptionTypes(); + + private static IEnumerable LoadKnownRuntimeExceptionTypes() + { + var result = new HashSet + { + + // ****************************************************************************************** + // CONFIRMED TYPES - these are for sure mapping to a type in Java that we want to catch + // ****************************************************************************************** + + typeof(SystemException), // Roughly corresponds to RuntimeException + + // Corresponds to IndexOutOfBoundsException, StringIndexOutOfBoundsException, and ArrayIndexOutOfBoundsException + typeof(IndexOutOfRangeException), + typeof(ArgumentOutOfRangeException), + typeof(Lucene.ArrayIndexOutOfBoundsException), + typeof(Lucene.IndexOutOfBoundsException), + typeof(Lucene.StringIndexOutOfBoundsException), + + // Corresponds to NullPointerException + typeof(NullReferenceException), + typeof(ArgumentNullException), + typeof(Lucene.NullPointerException), + + // Corresponds to IllegalArgumentException + typeof(ArgumentException), + typeof(Lucene.IllegalArgumentException), + + // Corresponds to UnsupportedOperationException + typeof(NotSupportedException), + typeof(Lucene.UnsupportedOperationException), + + // Corresponds to Lucene's ThreadInterruptedException + typeof(ThreadInterruptedException), + + // Corresponds to SecurityException + typeof(SecurityException), + + // Corresponds to ClassCastException + typeof(InvalidCastException), + + // Corresponds to IllegalStateException + typeof(InvalidOperationException), + typeof(Lucene.IllegalStateException), + + // Corresponds to MissingResourceException + typeof(MissingManifestResourceException), + + // Corresponds to NumberFormatException + typeof(FormatException), + typeof(Lucene.NumberFormatException), + + // Corresponds to ArithmeticException + typeof(ArithmeticException), + + // Corresponds to IllformedLocaleException + typeof(CultureNotFoundException), + + // Corresponds to JUnit's AssumptionViolatedException + typeof(NUnit.Framework.InconclusiveException), + + // Known implementations of IRuntimeException + + typeof(RuntimeException), + typeof(LuceneSystemException), + + typeof(BytesRefHash.MaxBytesLengthExceededException), + typeof(CollectionTerminatedException), + typeof(DocTermsIndexDocValues.DocTermsIndexException), + typeof(MergePolicy.MergeException), + typeof(SearcherExpiredException), + typeof(TimeLimitingCollector.TimeExceededException), + typeof(BooleanQuery.TooManyClausesException), + + // Other known runtime exceptions + typeof(AlreadySetException), // Subclasses InvalidOperationException + typeof(J2N.IO.BufferUnderflowException), + typeof(J2N.IO.BufferOverflowException), + typeof(J2N.IO.InvalidMarkException), + typeof(Lucene.Net.Spatial.Queries.UnsupportedSpatialOperation), // Subclasses NotSupportedException + + //typeof(NUnit.Framework.Internal.InvalidPlatformException), + + // ****************************************************************************************** + // UNCONFIRMED TYPES - these are SystemException types that are included, but require more + // research to determine whether they actually are something we don't want to catch as a RuntimeException. + // ****************************************************************************************** + + typeof(AccessViolationException), + typeof(AppDomainUnloadedException), + typeof(ArrayTypeMismatchException), + typeof(BadImageFormatException), + typeof(CannotUnloadAppDomainException), + typeof(KeyNotFoundException), + typeof(ContextMarshalException), + typeof(DataMisalignedException), + typeof(DivideByZeroException), // Subclasses ArithmeticException, so probably okay + typeof(DllNotFoundException), + typeof(DuplicateWaitObjectException), + typeof(EntryPointNotFoundException), +#pragma warning disable CS0618 // Type or member is obsolete + typeof(ExecutionEngineException), +#pragma warning restore CS0618 // Type or member is obsolete + typeof(InsufficientExecutionStackException), + typeof(InvalidProgramException), + typeof(InvalidDataException), + typeof(MulticastNotSupportedException), + typeof(NotFiniteNumberException), // Subclasses ArithmeticException, so probably okay + typeof(NotImplementedException), + typeof(OperationCanceledException), + typeof(OverflowException), // Subclasses ArithmeticException, so probably okay + typeof(PlatformNotSupportedException), + typeof(RankException), + typeof(System.Reflection.CustomAttributeFormatException), // Maybe like AnnotationTypeMismatchException in Java...? + typeof(System.Resources.MissingSatelliteAssemblyException), + //typeof(System.Runtime.CompilerServices.SwitchExpressionException), // .NET Standard 2.1+ only (conditionally added below) + typeof(System.Runtime.InteropServices.COMException), + typeof(System.Runtime.InteropServices.ExternalException), + typeof(System.Runtime.InteropServices.InvalidComObjectException), + typeof(System.Runtime.InteropServices.InvalidOleVariantTypeException), + typeof(System.Runtime.InteropServices.MarshalDirectiveException), + typeof(System.Runtime.InteropServices.SafeArrayRankMismatchException), + typeof(System.Runtime.InteropServices.SafeArrayTypeMismatchException), + typeof(System.Runtime.InteropServices.SEHException), + typeof(System.Runtime.Serialization.SerializationException), + typeof(System.Security.Cryptography.CryptographicException), + typeof(System.Security.VerificationException), + typeof(System.Text.DecoderFallbackException), // LUCENENET TODO: Need to be sure about this one + typeof(System.Text.EncoderFallbackException), // LUCENENET TODO: Need to be sure about this one + typeof(System.Threading.AbandonedMutexException), + typeof(System.Threading.SemaphoreFullException), + typeof(System.Threading.SynchronizationLockException), + typeof(System.Threading.Tasks.TaskCanceledException), + typeof(System.Threading.ThreadAbortException), + typeof(System.Threading.ThreadStartException), + typeof(System.Threading.ThreadStateException), + typeof(System.TimeoutException), + typeof(System.TypeAccessException), + typeof(System.TypeInitializationException), + typeof(System.TypeLoadException), + typeof(System.TypeUnloadedException), + }; + + // .NET Core 3.0 + only + if (!(SwitchExpressionExceptionType is null)) + { + result.Add(SwitchExpressionExceptionType); + } + + // .NET Framework only + if (!(RemotingExceptionType is null)) + { + result.Add(RemotingExceptionType); + } + if (!(RemotingTimeoutExceptionType is null)) + { + result.Add(RemotingTimeoutExceptionType); + } + if (!(RemotingServerExceptionType is null)) + { + result.Add(RemotingServerExceptionType); + } + if (!(CryptographicUnexpectedOperationExceptionType is null)) + { + result.Add(CryptographicUnexpectedOperationExceptionType); + } + if (!(HostProtectionExceptionType is null)) + { + result.Add(HostProtectionExceptionType); + } + if (!(PolicyExceptionType is null)) + { + result.Add(PolicyExceptionType); + } + if (!(IdentityNotMappedExceptionType is null)) + { + result.Add(IdentityNotMappedExceptionType); + } + if (!(XmlSyntaxExceptionType is null)) + { + result.Add(XmlSyntaxExceptionType); + } + + return result; + } + + #endregion Known types of exception families + + #region Special case constructors + + private static readonly IDictionary> NonStandardExceptionConstructors = LoadNonStandardExceptionConstructors(); + + private static IDictionary> LoadNonStandardExceptionConstructors() + { + var result = new Dictionary> + { + [typeof(NUnit.Framework.MultipleAssertException)] = (exceptionType, message) => + { + //public class MultipleAssertException : ResultStateException + //{ + // public MultipleAssertException(ITestResult testResult) + return Activator.CreateInstance( + typeof(NUnit.Framework.MultipleAssertException), + new object[] { new NUnitExceptionMessage(message) }); // NUnitExcpetionMessage implements NUnit.Framework.Interfaces.ITestResult + }, + [typeof(ReflectionTypeLoadException)] = (exceptionType, message) => + { + //public sealed class ReflectionTypeLoadException : SystemException + //{ + // public ReflectionTypeLoadException (Type?[]? classes, Exception?[]? exceptions) + Type[] types = new Type[] { typeof(Exception) }; + Exception[] exceptions = new Exception[] { new Exception() }; + return Activator.CreateInstance( + typeof(ReflectionTypeLoadException), + new object[] { types, exceptions }); + }, + [typeof(TargetInvocationException)] = (exceptionType, message) => + { + //public sealed class TargetInvocationException : ApplicationException + //{ + // public TargetInvocationException (string? message, Exception? inner) + return Activator.CreateInstance( + typeof(TargetInvocationException), + new object[] { message, new Exception() }); + }, + }; + + // Special case - this doesn't exist on .NET Framework, so we only add it if not null + if (!(DebugAssertExceptionType is null)) + { + result[DebugAssertExceptionType] = (exceptionType, message) => + { + //private sealed class DebugAssertException : Exception + //{ + // internal DebugAssertException(string? message, string? detailMessage, string? stackTrace) + BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance; + return Activator.CreateInstance(DebugAssertExceptionType, flags, null, new object[] { message, null, null }, CultureInfo.InvariantCulture); + }; + } + + if (!(MetadataExceptionType is null)) + { + result[MetadataExceptionType] = (exceptionType, message) => + { + //private sealed class MetadataException : Exception // NOTE: Couldn't find in the source, but this part doesn't matter so much + //{ + // internal MetadataException(int value) + BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance; + return Activator.CreateInstance(MetadataExceptionType, flags, null, new object[] { (int)0 }, CultureInfo.InvariantCulture); + }; + } + + if (!(CrossAppDomainMarshaledExceptionType is null)) + { + result[CrossAppDomainMarshaledExceptionType] = (exceptionType, message) => + { + //private sealed class CrossAppDomainMarshaledException : Exception // NOTE: Couldn't find in the source, but this part doesn't matter so much + //{ + // internal CrossAppDomainMarshaledException(string message, int value) + BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance; + return Activator.CreateInstance(CrossAppDomainMarshaledExceptionType, flags, null, new object[] { message, (int)0 }, CultureInfo.InvariantCulture); + }; + } + + return result; + } + + public class NUnitExceptionMessage : NUnit.Framework.Interfaces.ITestResult + { + private readonly string message; + + public NUnitExceptionMessage(string message) + { + this.message = message ?? throw new ArgumentException(nameof(message)); + } + + public string Message => message; + + #region Unneeded Members + public ResultState ResultState => throw new NotImplementedException(); + + public string Name => throw new NotImplementedException(); + + public string FullName => throw new NotImplementedException(); + + public double Duration => throw new NotImplementedException(); + + public DateTime StartTime => throw new NotImplementedException(); + + public DateTime EndTime => throw new NotImplementedException(); + + public string StackTrace => throw new NotImplementedException(); + + public int TotalCount => throw new NotImplementedException(); + + public int AssertCount => throw new NotImplementedException(); + + public int FailCount => throw new NotImplementedException(); + + public int WarningCount => throw new NotImplementedException(); + + public int PassCount => throw new NotImplementedException(); + + public int SkipCount => throw new NotImplementedException(); + + public int InconclusiveCount => throw new NotImplementedException(); + + public bool HasChildren => throw new NotImplementedException(); + + public IEnumerable Children => throw new NotImplementedException(); + + public ITest Test => throw new NotImplementedException(); + + public string Output => throw new NotImplementedException(); + + public IList AssertionResults => throw new NotImplementedException(); + + public ICollection TestAttachments => throw new NotImplementedException(); + + public TNode AddToXml(TNode parentNode, bool recursive) => throw new NotImplementedException(); + public TNode ToXml(bool recursive) => throw new NotImplementedException(); + + #endregion Unneeded Members + } + + #endregion Special case constructors + + + private static ICollection LoadTypesSubclassing(Type baseClass, params Assembly[] assemblies) + { + if (baseClass is null) + throw new ArgumentNullException(nameof(baseClass)); + if (assemblies is null) + throw new ArgumentNullException(nameof(assemblies)); + + var result = new JCG.SortedSet(Comparer.Create((left, right) => left.Name.CompareToOrdinal(right.Name))); + foreach (var assembly in assemblies) + { + result.UnionWith(assembly.GetTypes().Where(exceptionType => baseClass.IsAssignableFrom(exceptionType))); + } + return result; + } + + public static IEnumerable ThrowableTypeExpressions + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownThrowableExceptionTypes.Contains(exceptionType), // expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + + public static IEnumerable ErrorTypeExpressions + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownErrorExceptionTypes.Contains(exceptionType), // expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + public static IEnumerable ExceptionTypeExpressions + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownExceptionTypes.Contains(exceptionType), // expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + public static IEnumerable RuntimeExceptionTypeExpressions + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { +#if NETCOREAPP2_1 + // These don't seem to match on .NET Core 2.1, but we don't care + if (exceptionType.FullName.Equals("System.CrossAppDomainMarshaledException") || + exceptionType.FullName.Equals("System.AppDomainUnloadedException")) + { + continue; + } +#endif + + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownRuntimeExceptionTypes.Contains(exceptionType),// expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + public static IEnumerable IOExceptionTypeExpressions + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownIOExceptionTypes.Contains(exceptionType), // expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + public static IEnumerable AssertionErrorTypeExpressions + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownAssertionErrorTypes.Contains(exceptionType), // expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + public static IEnumerable IndexOutOfBoundsExceptionTypeExpressions + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownIndexOutOfBoundsExceptionTypes.Contains(exceptionType), // expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + public static IEnumerable NullPointerExceptionTypeExpressions + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownNullPointerExceptionTypes.Contains(exceptionType), // expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + public static IEnumerable IllegalArgumentExceptionTypeExpressions + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownIllegalArgumentExceptionTypes.Contains(exceptionType), // expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + public static IEnumerable IllegalArgumentExceptionTypeExpressions_TestEnvironment + { + get + { + foreach (var exceptionType in AllExceptionTypes) + { + // expectedToThrow is true when we expect the error to be thrown and false when we expect it to be caught + yield return new TestCaseData( + exceptionType, // exception type (to make NUnit display them all) + !KnownIllegalArgumentExceptionTypes_TestEnvironment.Contains(exceptionType), // expectedToThrow + new Action(() => ThrowException(exceptionType))); // throw exception expression + } + } + } + + private static void ThrowException(Type exceptionType) + { + object exception = null; + if (NonStandardExceptionConstructors.TryGetValue(exceptionType, out Func constructionFactory)) + { + try + { + exception = constructionFactory(exceptionType, $"Throwing a {exceptionType.Name}."); + } + catch (MissingMethodException ex) + { + Assert.Fail($"Can't instantiate type {exceptionType.Name}, it's missing the necessary constructors.:\n\n{ex}"); + } + } + else + { + BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance; + try + { + exception = Activator.CreateInstance(exceptionType, flags, null, new object[] { $"Throwing a {exceptionType.Name}." }, CultureInfo.InvariantCulture); + } + catch (MissingMethodException) + { + try + { + exception = Activator.CreateInstance(exceptionType, flags, null, null, CultureInfo.InvariantCulture); + } + catch (MissingMethodException ex) + { + Assert.Fail($"Can't instantiate type {exceptionType.Name}, it's missing the necessary constructors.:\n\n{ex}"); + } + } + } + throw (Exception)exception; + } + + [Test] + [TestCaseSource("ThrowableTypeExpressions")] + public void TestIsThrowable(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + static bool extensionMethod(Exception e) => e.IsThrowable(); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + [Test] + [TestCaseSource("ErrorTypeExpressions")] + public void TestIsError(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + static bool extensionMethod(Exception e) => e.IsError(); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + // This test ensures that all known Error types from Java are not caught by + // our IsException() handler. + [Test] + [TestCaseSource("ExceptionTypeExpressions")] + public void TestIsException(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + static bool extensionMethod(Exception e) => e.IsException(); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + // This test ensures that all known Error types from Java are not caught by + // our IsRuntimeException() handler. + [Test] + [TestCaseSource("RuntimeExceptionTypeExpressions")] + public void TestIsRuntimeException(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + static bool extensionMethod(Exception e) => e.IsRuntimeException(); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + [Test] + [TestCaseSource("IOExceptionTypeExpressions")] + public void TestIsIOException(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + static bool extensionMethod(Exception e) => e.IsIOException(); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + // This test ensures that Lucene.NET's AssertionException, the .NET platform's DebugAssertException, and + // NUnit's AssertionException and MultipleAssertException types are all treated as if they were AssertionError + // in Java. + [Test] + [TestCaseSource("AssertionErrorTypeExpressions")] + public void TestIsAssertionError(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + static bool extensionMethod(Exception e) => e.IsAssertionError(); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + // This test ensures that ArgumentOutOfRangeException and IndexOutOfRangeException are both caught by our + // IndexOutOfBoundsException handler, because they both correspond to IndexOutOfBoundsException in Java. + // Java has 2 other types ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException, whose alias + // exception types are also part of the test. + [Test] + [TestCaseSource("IndexOutOfBoundsExceptionTypeExpressions")] + public void TestIsIndexOutOfBoundsException(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + static bool extensionMethod(Exception e) => e.IsIndexOutOfBoundsException(); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + // This test ensures that ArgumentNullException and NullReferenceException are both caught by our + // NullPointerException handler, because they both correspond to NullPointerException in Java + [Test] + [TestCaseSource("NullPointerExceptionTypeExpressions")] + public void TestIsNullPointerException(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + static bool extensionMethod(Exception e) => e.IsNullPointerException(); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + // This test ensures that any known ArgumentException will be caught. + // We do it this way in production to ensure that if we "upgrade" to a .NET + // ArgumentNullException or ArgumentOutOfRangeException it won't break the code. + [Test] + [TestCaseSource("IllegalArgumentExceptionTypeExpressions")] + public void TestIsIllegalArgumentException(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + // Make sure we are testing the production code + static bool extensionMethod(Exception e) => Lucene.ExceptionExtensions.IsIllegalArgumentException(e); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + // This test ensures that ArgumentNullException and ArgumentOutOfRangeException are not caught by our + // IllegalArgumentException handler in tests, because they wouldn't be in Java. We do this differently + // in the test environment to ensure that if a test is specified wrong it will fail and should be updated + // and commented to indicate we diverged from Lucene. + [Test] + [TestCaseSource("IllegalArgumentExceptionTypeExpressions_TestEnvironment")] + public void TestIsIllegalArgumentException_TestEnvironment(Type exceptionType, bool expectedToThrow, Action expression) // LUCENENET NOTE: exceptionType is only here to make NUnit display them all + { + // Make sure we are testing the test environment code + static bool extensionMethod(Exception e) => Lucene.Net.ExceptionExtensions.IsIllegalArgumentException(e); + + if (expectedToThrow) + { + AssertDoesNotCatch(expression, extensionMethod); + } + else + { + AssertCatches(expression, extensionMethod); + } + } + + private void AssertCatches(Action action, Func extensionMethodExpression) + { + try + { + try + { + action(); + } + catch (Exception e) when (extensionMethodExpression(e)) + { + // expected + Assert.Pass($"Expected: Caught exception {e.GetType().FullName}"); + } + } + catch (Exception e) when (!(e is NUnit.Framework.SuccessException)) + { + // not expected + Assert.Fail($"Exception thrown when expected to be caught: {e.GetType().FullName}"); + } + } + + private void AssertDoesNotCatch(Action action, Func extensionMethodExpression) + { + try + { + try + { + action(); + } + catch (NUnit.Framework.AssertionException e) + { + // Special case - need to suppress this from being thrown to the outer catch + // or we will get a false failure + Assert.IsFalse(extensionMethodExpression(e)); + Assert.Pass($"Expected: Did not catch exception {e.GetType().FullName}"); + } + catch (Exception e) when (extensionMethodExpression(e)) + { + // not expected + Assert.Fail($"Exception caught when expected to be thrown: {e.GetType().FullName}"); + } + } + catch (Exception e) when (!(e is NUnit.Framework.AssertionException)) + { + // expected + Assert.Pass($"Expected: Did not catch exception {e.GetType().FullName}"); + } + } + } +} diff --git a/src/Lucene.Net.Tests/Support/TestApiConsistency.cs b/src/Lucene.Net.Tests/Support/TestApiConsistency.cs index f10100f2dc..8f8a50ab43 100644 --- a/src/Lucene.Net.Tests/Support/TestApiConsistency.cs +++ b/src/Lucene.Net.Tests/Support/TestApiConsistency.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Attributes; +using Lucene.Net.Attributes; using Lucene.Net.Util; using NUnit.Framework; using System; @@ -38,7 +38,7 @@ public override void TestProtectedFieldNames(Type typeFromTargetAssembly) [TestCase(typeof(Lucene.Net.Analysis.Analyzer))] public override void TestPrivateFieldNames(Type typeFromTargetAssembly) { - base.TestPrivateFieldNames(typeFromTargetAssembly, @"^Lucene\.Net\.Support\.(?:ConcurrentHashSet|PlatformHelper)"); + base.TestPrivateFieldNames(typeFromTargetAssembly, @"^Lucene\.Net\.Support\.(?:ConcurrentHashSet|PlatformHelper)|^Lucene\.ExceptionExtensions"); } [Test, LuceneNetSpecific] diff --git a/src/Lucene.Net.Tests/Support/TestWeakDictionary.cs b/src/Lucene.Net.Tests/Support/TestWeakDictionary.cs index 8a42a6df2c..f059139f89 100644 --- a/src/Lucene.Net.Tests/Support/TestWeakDictionary.cs +++ b/src/Lucene.Net.Tests/Support/TestWeakDictionary.cs @@ -1,4 +1,4 @@ -#if !FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR +#if !FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR using Lucene.Net.Attributes; using Lucene.Net.Util; using NUnit.Framework; @@ -100,9 +100,7 @@ public void B_TestOutOfMemory() if (i % 1024 == 0) Console.WriteLine("Requested Mem: " + i.ToString() + " MB"); OOMECount = 0; } -#pragma warning disable 168 - catch (OutOfMemoryException oom) -#pragma warning restore 168 + catch (Exception oom) when (oom.IsOutOfMemoryError()) { if (OOMECount++ > 10) throw new Exception("Memory Allocation Error in B_TestOutOfMemory"); //Try Again. GC will eventually release some memory. diff --git a/src/Lucene.Net.Tests/TestAssertions.cs b/src/Lucene.Net.Tests/TestAssertions.cs index 929354fb78..6a4ca20156 100644 --- a/src/Lucene.Net.Tests/TestAssertions.cs +++ b/src/Lucene.Net.Tests/TestAssertions.cs @@ -1,4 +1,4 @@ -// LUCENENET: Rather than using AssertFinal() to run Reflection code at runtime, +// LUCENENET: Rather than using AssertFinal() to run Reflection code at runtime, // we are using a Roslyn code analyzer to ensure the rules are followed at compile time. //using System.Diagnostics; @@ -70,7 +70,7 @@ // var c = new TestTokenStream3(); // doFail = true; // } -// catch (InvalidOperationException) +// catch (Exception e) when (e.IsAssertionError()) // { // // expected // } diff --git a/src/Lucene.Net.Tests/TestWorstCaseTestBehavior.cs b/src/Lucene.Net.Tests/TestWorstCaseTestBehavior.cs index a3886a38b5..a6c9298fc4 100644 --- a/src/Lucene.Net.Tests/TestWorstCaseTestBehavior.cs +++ b/src/Lucene.Net.Tests/TestWorstCaseTestBehavior.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Util; using NUnit.Framework; using System; @@ -58,7 +58,7 @@ public override void Run() { Thread.Sleep(10000); } - catch (ThreadInterruptedException) + catch (Exception e) when (e.IsInterruptedException()) { // Ignore. } @@ -118,7 +118,7 @@ public ThreadAnonymousClass2(TestWorstCaseTestBehavior outerInstance) public override void Run() { - throw new Exception("foobar"); + throw RuntimeException.Create("foobar"); } } @@ -140,7 +140,7 @@ public virtual void TestZombie() { Thread.Sleep(1000); } - catch (ThreadInterruptedException) + catch (Exception e) when (e.IsInterruptedException()) { } } diff --git a/src/Lucene.Net.Tests/Util/Automaton/TestBasicOperations.cs b/src/Lucene.Net.Tests/Util/Automaton/TestBasicOperations.cs index 121e830f87..38979467eb 100644 --- a/src/Lucene.Net.Tests/Util/Automaton/TestBasicOperations.cs +++ b/src/Lucene.Net.Tests/Util/Automaton/TestBasicOperations.cs @@ -162,7 +162,7 @@ public virtual void TestGetRandomAcceptedString() string s = UnicodeUtil.NewString(acc, 0, acc.Length); Assert.IsTrue(BasicOperations.Run(a, s)); } - catch (Exception /*t*/) + catch (Exception t) when (t.IsThrowable()) { Console.WriteLine("regexp: " + re); if (acc != null) diff --git a/src/Lucene.Net.Tests/Util/Automaton/TestUTF32ToUTF8.cs b/src/Lucene.Net.Tests/Util/Automaton/TestUTF32ToUTF8.cs index 5463cc601e..21656909ba 100644 --- a/src/Lucene.Net.Tests/Util/Automaton/TestUTF32ToUTF8.cs +++ b/src/Lucene.Net.Tests/Util/Automaton/TestUTF32ToUTF8.cs @@ -271,7 +271,7 @@ private static void AssertAutomaton(Automaton automaton) { s = UnicodeUtil.NewString(codepoints, 0, codepoints.Length); } - catch (Exception /*e*/) + catch (Exception e) when (e.IsException()) { Console.WriteLine(codepoints.Length + " codepoints:"); for (int j = 0; j < codepoints.Length; j++) diff --git a/src/Lucene.Net.Tests/Util/Fst/TestFSTs.cs b/src/Lucene.Net.Tests/Util/Fst/TestFSTs.cs index f4dfb75b99..8a1fc867ff 100644 --- a/src/Lucene.Net.Tests/Util/Fst/TestFSTs.cs +++ b/src/Lucene.Net.Tests/Util/Fst/TestFSTs.cs @@ -393,9 +393,7 @@ public virtual void TestRealTerms() { var _ = termsEnum.Ord; } -#pragma warning disable 168, IDE0059 - catch (NotSupportedException uoe) -#pragma warning restore 168, IDE0059 + catch (Exception uoe) when (uoe.IsUnsupportedOperationException()) { if (Verbose) { @@ -640,11 +638,11 @@ public virtual void Run(int limit, bool verify, bool verifyByOutput) T actual = Util.Get(fst, intsRef); if (actual == null) { - throw new Exception("unexpected null output on input=" + w); + throw RuntimeException.Create("unexpected null output on input=" + w); } if (!actual.Equals(expected)) { - throw new Exception("wrong output (got " + outputs.OutputToString(actual) + " but expected " + outputs.OutputToString(expected) + ") on input=" + w); + throw RuntimeException.Create("wrong output (got " + outputs.OutputToString(actual) + " but expected " + outputs.OutputToString(expected) + ") on input=" + w); } } else @@ -654,11 +652,11 @@ public virtual void Run(int limit, bool verify, bool verifyByOutput) Int32sRef actual = Util.GetByOutput(fst as FST, output.GetValueOrDefault()); if (actual == null) { - throw new Exception("unexpected null input from output=" + output); + throw RuntimeException.Create("unexpected null input from output=" + output); } if (!actual.Equals(intsRef)) { - throw new Exception("wrong input (got " + actual + " but expected " + intsRef + " from output=" + output); + throw RuntimeException.Create("wrong input (got " + actual + " but expected " + intsRef + " from output=" + output); } } diff --git a/src/Lucene.Net.Tests/Util/Packed/TestPackedInts.cs b/src/Lucene.Net.Tests/Util/Packed/TestPackedInts.cs index e8c480150e..2660e5cc9b 100644 --- a/src/Lucene.Net.Tests/Util/Packed/TestPackedInts.cs +++ b/src/Lucene.Net.Tests/Util/Packed/TestPackedInts.cs @@ -382,9 +382,9 @@ private static void AssertRandomEquality(int valueCount, int bitsPerValue, long { Fill(packedInt, PackedInt32s.MaxValue(bitsPerValue), randomSeed); } - catch (Exception e) + catch (Exception e) when (e.IsException()) { - Console.Error.WriteLine(e.StackTrace); + e.printStackTrace(Console.Error); Assert.Fail(string.Format(CultureInfo.InvariantCulture, "Exception while filling {0}: valueCount={1}, bitsPerValue={2}", packedInt.GetType().Name, valueCount, bitsPerValue)); } } @@ -520,9 +520,7 @@ public virtual void TestIntOverflow() { p64 = new Packed64(INDEX, BITS); } -#pragma warning disable 168 - catch (OutOfMemoryException oome) -#pragma warning restore 168 + catch (Exception oome) when (oome.IsOutOfMemoryError()) { // this can easily happen: we're allocating a // long[] that needs 256-273 MB. Heap is 512 MB, @@ -542,9 +540,7 @@ public virtual void TestIntOverflow() { p64sb = Packed64SingleBlock.Create(INDEX, BITS); } -#pragma warning disable 168 - catch (OutOfMemoryException oome) -#pragma warning restore 168 + catch (Exception oome) when (oome.IsOutOfMemoryError()) { // Ignore: see comment above } @@ -560,9 +556,7 @@ public virtual void TestIntOverflow() { p8 = new Packed8ThreeBlocks(index); } -#pragma warning disable 168 - catch (OutOfMemoryException oome) -#pragma warning restore 168 + catch (Exception oome) when (oome.IsOutOfMemoryError()) { // Ignore: see comment above } @@ -579,9 +573,7 @@ public virtual void TestIntOverflow() { p16 = new Packed16ThreeBlocks(index); } -#pragma warning disable 168 - catch (OutOfMemoryException oome) -#pragma warning restore 168 + catch (Exception oome) when (oome.IsOutOfMemoryError()) { // Ignore: see comment above } @@ -1157,7 +1149,7 @@ public virtual void TestAppendingLongBuffer() inc = TestUtil.NextInt32(Random, -1000, 1000); break; default: - throw new Exception("added a type and forgot to add it here?"); + throw RuntimeException.Create("added a type and forgot to add it here?"); } @@ -1377,9 +1369,7 @@ public virtual void TestBlockPackedReaderWriter() it.Next(); Assert.IsTrue(false); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // OK } @@ -1416,9 +1406,7 @@ public virtual void TestBlockPackedReaderWriter() it2.Skip(1); Assert.IsTrue(false); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { // OK } diff --git a/src/Lucene.Net.Tests/Util/StressRamUsageEstimator.cs b/src/Lucene.Net.Tests/Util/StressRamUsageEstimator.cs index db966c2527..769a1f92ab 100644 --- a/src/Lucene.Net.Tests/Util/StressRamUsageEstimator.cs +++ b/src/Lucene.Net.Tests/Util/StressRamUsageEstimator.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using NUnit.Framework; using System; using System.Globalization; @@ -68,9 +68,7 @@ public virtual void TestChainedEstimation() } } } -#pragma warning disable 168 - catch (OutOfMemoryException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsOutOfMemoryError()) { // Release and quit. } @@ -151,9 +149,7 @@ public virtual void TestSimpleByteArrays() } } } -#pragma warning disable 168 - catch (OutOfMemoryException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsOutOfMemoryError()) { // Release and quit. } diff --git a/src/Lucene.Net.Tests/Util/TestArrayUtil.cs b/src/Lucene.Net.Tests/Util/TestArrayUtil.cs index 86bf42e7a5..4a56a15e3c 100644 --- a/src/Lucene.Net.Tests/Util/TestArrayUtil.cs +++ b/src/Lucene.Net.Tests/Util/TestArrayUtil.cs @@ -83,9 +83,7 @@ public virtual void TestParseInt() test = ArrayUtil.ParseInt32("".ToCharArray()); Assert.IsTrue(false); } -#pragma warning disable 168 - catch (FormatException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsNumberFormatException()) { //expected } @@ -94,9 +92,7 @@ public virtual void TestParseInt() test = ArrayUtil.ParseInt32("foo".ToCharArray()); Assert.IsTrue(false); } -#pragma warning disable 168 - catch (FormatException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsNumberFormatException()) { //expected } @@ -105,9 +101,7 @@ public virtual void TestParseInt() test = ArrayUtil.ParseInt32(Convert.ToString(long.MaxValue).ToCharArray()); Assert.IsTrue(false); } -#pragma warning disable 168 - catch (FormatException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsNumberFormatException()) { //expected } @@ -116,9 +110,7 @@ public virtual void TestParseInt() test = ArrayUtil.ParseInt32("0.34".ToCharArray()); Assert.IsTrue(false); } -#pragma warning disable 168 - catch (FormatException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsNumberFormatException()) { //expected } @@ -136,7 +128,7 @@ public virtual void TestParseInt() test = ArrayUtil.ParseInt32("foo 1923 bar".ToCharArray(), 4, 4); Assert.IsTrue(test == 1923, test + " does not equal: " + 1923); } - catch (FormatException e) + catch (Exception e) when (e.IsNumberFormatException()) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); diff --git a/src/Lucene.Net.Tests/Util/TestAttributeSource.cs b/src/Lucene.Net.Tests/Util/TestAttributeSource.cs index 75546dda5c..4f4f7ba18e 100644 --- a/src/Lucene.Net.Tests/Util/TestAttributeSource.cs +++ b/src/Lucene.Net.Tests/Util/TestAttributeSource.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Analysis.TokenAttributes; +using Lucene.Net.Analysis.TokenAttributes; using NUnit.Framework; using System; using System.Collections.Generic; @@ -80,9 +80,7 @@ public virtual void TestCaptureState() src3.RestoreState(state); Assert.Fail("The third instance is missing the TypeAttribute, so restoreState() should throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // pass } @@ -147,9 +145,7 @@ public virtual void TestInvalidArguments() src.AddAttribute(); Assert.Fail("Should throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { } @@ -159,9 +155,7 @@ public virtual void TestInvalidArguments() src.AddAttribute(); Assert.Fail("Should throw IllegalArgumentException"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { } @@ -176,7 +170,7 @@ public virtual void TestInvalidArguments() src.AddAttribute(); Assert.Fail("Should throw IllegalArgumentException"); } - catch (ArgumentException iae) + catch (Exception iae) when (iae.IsIllegalArgumentException()) { }*/ } diff --git a/src/Lucene.Net.Tests/Util/TestCharsRef.cs b/src/Lucene.Net.Tests/Util/TestCharsRef.cs index c2a59b8c8b..1246e3877a 100644 --- a/src/Lucene.Net.Tests/Util/TestCharsRef.cs +++ b/src/Lucene.Net.Tests/Util/TestCharsRef.cs @@ -1,4 +1,4 @@ -using J2N.Text; +using J2N.Text; using Lucene.Net.Attributes; using NUnit.Framework; using System; @@ -133,7 +133,7 @@ public virtual void TestCopyCharsRef() // c.CharAt(-1); // Assert.Fail(); // } - // catch (IndexOutOfRangeException expected) + // catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) // { // // expected exception // } @@ -143,7 +143,7 @@ public virtual void TestCopyCharsRef() // c.CharAt(3); // Assert.Fail(); // } - // catch (IndexOutOfRangeException expected) + // catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) // { // // expected exception // } @@ -162,9 +162,7 @@ public virtual void TestCharSequenceIndexer() var _ = c[-1]; Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { // expected exception } @@ -174,9 +172,7 @@ public virtual void TestCharSequenceIndexer() var _ = c[3]; Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { // expected exception } @@ -216,9 +212,7 @@ private void DoTestSequence(ICharSequence c) c.Subsequence(-1, 1 - -1); // LUCENENET: Corrected 2nd parameter Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { // expected exception } @@ -228,9 +222,7 @@ private void DoTestSequence(ICharSequence c) c.Subsequence(0, -1 - 0); // LUCENENET: Corrected 2nd parameter Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { // expected exception } @@ -240,9 +232,7 @@ private void DoTestSequence(ICharSequence c) c.Subsequence(0, 4 - 0); // LUCENENET: Corrected 2nd parameter Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { // expected exception } @@ -252,9 +242,7 @@ private void DoTestSequence(ICharSequence c) c.Subsequence(2, 1 - 2); // LUCENENET: Corrected 2nd parameter Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentOutOfRangeException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIndexOutOfBoundsException()) { // expected exception } diff --git a/src/Lucene.Net.Tests/Util/TestDoubleBarrelLRUCache.cs b/src/Lucene.Net.Tests/Util/TestDoubleBarrelLRUCache.cs index 2325cb21b1..a0b1e4dd0a 100644 --- a/src/Lucene.Net.Tests/Util/TestDoubleBarrelLRUCache.cs +++ b/src/Lucene.Net.Tests/Util/TestDoubleBarrelLRUCache.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -125,10 +125,10 @@ public override void Run() outerInstance.AddResults(miss, hit); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { failed = true; - throw new Exception(t.Message, t); + throw RuntimeException.Create(t); } } } diff --git a/src/Lucene.Net.Tests/Util/TestFilterIterator.cs b/src/Lucene.Net.Tests/Util/TestFilterIterator.cs index fafe3a6cf3..4c6751f5b7 100644 --- a/src/Lucene.Net.Tests/Util/TestFilterIterator.cs +++ b/src/Lucene.Net.Tests/Util/TestFilterIterator.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using System.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; @@ -118,7 +118,7 @@ public virtual void TestAll2() // it.Remove(); // Assert.Fail("Should throw UnsupportedOperationException"); // } - // catch (NotSupportedException) + // catch (Exception oue) when (oue.IsUnsupportedOperationException()) // { // // pass // } diff --git a/src/Lucene.Net.Tests/Util/TestIOUtils.cs b/src/Lucene.Net.Tests/Util/TestIOUtils.cs index 9e85de9e5a..bc8ae8621e 100644 --- a/src/Lucene.Net.Tests/Util/TestIOUtils.cs +++ b/src/Lucene.Net.Tests/Util/TestIOUtils.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using System.IO; using Assert = Lucene.Net.TestFramework.Assert; @@ -64,11 +64,9 @@ public virtual void TestSuppressedExceptions() assertEquals("TEST-IO-EXCEPTION-1", e1.GetSuppressed()[0].Message); assertEquals("TEST-IO-EXCEPTION-2", e1.GetSuppressed()[1].Message); } -#pragma warning disable 168 - catch (Exception e2) -#pragma warning restore 168 + catch (Exception e2) when (e2.IsIOException()) { - Assert.Fail("Exception should not be thrown here"); + Assert.Fail("IOException should not be thrown here"); } // test without prior exception @@ -82,7 +80,7 @@ public virtual void TestSuppressedExceptions() { fail("TestException should not be thrown here"); } - catch (IOException e2) + catch (Exception e2) when (e2.IsIOException()) { assertEquals("TEST-IO-EXCEPTION-1", e2.Message); assertEquals(1, e2.GetSuppressed().Length); diff --git a/src/Lucene.Net.Tests/Util/TestNamedSPILoader.cs b/src/Lucene.Net.Tests/Util/TestNamedSPILoader.cs index f6b1f51222..57a7446ce4 100644 --- a/src/Lucene.Net.Tests/Util/TestNamedSPILoader.cs +++ b/src/Lucene.Net.Tests/Util/TestNamedSPILoader.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -44,9 +44,7 @@ public virtual void TestBogusLookup() Codec.ForName("dskfdskfsdfksdfdsf"); Assert.Fail(); } -#pragma warning disable 168 - catch (ArgumentException expected) -#pragma warning restore 168 + catch (Exception expected) when (expected.IsIllegalArgumentException()) { } } diff --git a/src/Lucene.Net.Tests/Util/TestNumericUtils.cs b/src/Lucene.Net.Tests/Util/TestNumericUtils.cs index 293805e2db..7f3a0eaa67 100644 --- a/src/Lucene.Net.Tests/Util/TestNumericUtils.cs +++ b/src/Lucene.Net.Tests/Util/TestNumericUtils.cs @@ -95,9 +95,7 @@ public virtual void TestLongSpecialValues() NumericUtils.PrefixCodedToInt32(prefixVals[i]); Assert.Fail("decoding a prefix coded long value as int should fail"); } -#pragma warning disable 168 - catch (FormatException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsNumberFormatException()) { // worked } @@ -143,9 +141,7 @@ public virtual void TestIntSpecialValues() NumericUtils.PrefixCodedToInt64(prefixVals[i]); Assert.Fail("decoding a prefix coded int value as long should fail"); } -#pragma warning disable 168 - catch (FormatException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsNumberFormatException()) { // worked } diff --git a/src/Lucene.Net.Tests/Util/TestOfflineSorter.cs b/src/Lucene.Net.Tests/Util/TestOfflineSorter.cs index d267658fdf..a21505529b 100644 --- a/src/Lucene.Net.Tests/Util/TestOfflineSorter.cs +++ b/src/Lucene.Net.Tests/Util/TestOfflineSorter.cs @@ -1,4 +1,4 @@ -using J2N.Text; +using J2N.Text; using NUnit.Framework; using System; using System.Collections.Generic; @@ -195,9 +195,10 @@ public virtual void TestRamBuffer() OfflineSorter.BufferSize.Megabytes(2047); OfflineSorter.BufferSize.Megabytes(1); - Assert.Throws(() => OfflineSorter.BufferSize.Megabytes(2048), "max mb is 2047"); - Assert.Throws(() => OfflineSorter.BufferSize.Megabytes(0), "min mb is 0.5"); - Assert.Throws(() => OfflineSorter.BufferSize.Megabytes(-1), "min mb is 0.5"); + // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) + Assert.Throws(() => OfflineSorter.BufferSize.Megabytes(2048), "max mb is 2047"); + Assert.Throws(() => OfflineSorter.BufferSize.Megabytes(0), "min mb is 0.5"); + Assert.Throws(() => OfflineSorter.BufferSize.Megabytes(-1), "min mb is 0.5"); } } } \ No newline at end of file diff --git a/src/Lucene.Net.Tests/Util/TestPriorityQueue.cs b/src/Lucene.Net.Tests/Util/TestPriorityQueue.cs index da598ae4b8..d55900295f 100644 --- a/src/Lucene.Net.Tests/Util/TestPriorityQueue.cs +++ b/src/Lucene.Net.Tests/Util/TestPriorityQueue.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Attributes; +using Lucene.Net.Attributes; using NUnit.Framework; using System; using System.Collections.Generic; @@ -228,7 +228,7 @@ public static void TestMaxSizeBounds() // Should had thrown an exception Assert.Fail(); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { } @@ -237,7 +237,7 @@ public static void TestMaxSizeBounds() { pq = new IntegerQueue(maxSize); } - catch (ArgumentException) + catch (Exception e) when (e.IsIllegalArgumentException()) { } } @@ -417,7 +417,7 @@ public static void TestOverflow() pq.Add(3); Assert.Fail(); } - catch (IndexOutOfRangeException) + catch (Exception e) when (e.IsIndexOutOfBoundsException()) { } @@ -434,7 +434,7 @@ public static void TestOverflow() { pq.Add(666); } - catch (IndexOutOfRangeException) + catch (Exception e) when (e.IsIndexOutOfBoundsException()) { } } diff --git a/src/Lucene.Net.Tests/Util/TestRamUsageEstimatorOnWildAnimals.cs b/src/Lucene.Net.Tests/Util/TestRamUsageEstimatorOnWildAnimals.cs index 3604cc6fd2..6d4f309b30 100644 --- a/src/Lucene.Net.Tests/Util/TestRamUsageEstimatorOnWildAnimals.cs +++ b/src/Lucene.Net.Tests/Util/TestRamUsageEstimatorOnWildAnimals.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -54,9 +54,7 @@ public virtual void TestOverflowMaxChainLength() RamUsageEstimator.SizeOf(first); // cause SOE or pass. lower = mid; } -#pragma warning disable 168 - catch (StackOverflowException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsStackOverflowError()) { upper = mid; } diff --git a/src/Lucene.Net.Tests/Util/TestSetOnce.cs b/src/Lucene.Net.Tests/Util/TestSetOnce.cs index af81729f48..1608df5f5f 100644 --- a/src/Lucene.Net.Tests/Util/TestSetOnce.cs +++ b/src/Lucene.Net.Tests/Util/TestSetOnce.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using NUnit.Framework; using System; using System.Globalization; @@ -56,11 +56,11 @@ public override void Run() set.Set(new Integer(Convert.ToInt32(Name.Substring(2), CultureInfo.InvariantCulture))); success = true; } - catch (ThreadInterruptedException) + catch (Exception e) when (e.IsInterruptedException()) { // ignore } - catch (Exception) + catch (Exception e) when (e.IsRuntimeException()) { // TODO: change exception type // expected. diff --git a/src/Lucene.Net.Tests/Util/TestUnicodeUtil.cs b/src/Lucene.Net.Tests/Util/TestUnicodeUtil.cs index b3a19d025e..fd1f8210ff 100644 --- a/src/Lucene.Net.Tests/Util/TestUnicodeUtil.cs +++ b/src/Lucene.Net.Tests/Util/TestUnicodeUtil.cs @@ -1,4 +1,4 @@ -using J2N; +using J2N; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -146,9 +146,7 @@ private static void AssertcodePointCountThrowsAssertionOn(params byte[] bytes) { UnicodeUtil.CodePointCount(new BytesRef(bytes)); } -#pragma warning disable 168 - catch (ArgumentException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIllegalArgumentException()) { threwAssertion = true; } @@ -219,15 +217,11 @@ public virtual void TestNewString() Assert.AreEqual(cpString.Substring(rs, rc), str); continue; } -#pragma warning disable 168 - catch (IndexOutOfRangeException e1) -#pragma warning restore 168 + catch (Exception e1) when (e1.IsIndexOutOfBoundsException()) { // Ignored. } -#pragma warning disable 168 - catch (ArgumentException e2) -#pragma warning restore 168 + catch (Exception e2) when (e2.IsIllegalArgumentException()) { // Ignored. } diff --git a/src/Lucene.Net.Tests/Util/TestVirtualMethod.cs b/src/Lucene.Net.Tests/Util/TestVirtualMethod.cs index a1fe2e0fa7..0ac7841410 100644 --- a/src/Lucene.Net.Tests/Util/TestVirtualMethod.cs +++ b/src/Lucene.Net.Tests/Util/TestVirtualMethod.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; @@ -109,9 +109,7 @@ public virtual void TestExceptions() publicTestMethod.GetImplementationDistance(typeof(LuceneTestCase)); Assert.Fail("LuceneTestCase is not a subclass and can never override publicTest(String)"); } -#pragma warning disable 168 - catch (ArgumentException arg) -#pragma warning restore 168 + catch (Exception arg) when (arg.IsIllegalArgumentException()) { // pass } @@ -121,9 +119,7 @@ public virtual void TestExceptions() new VirtualMethod(typeof(BaseTestVirtualMethod), "bogus"); Assert.Fail("Method bogus() does not exist, so IAE should be thrown"); } -#pragma warning disable 168 - catch (ArgumentException arg) -#pragma warning restore 168 + catch (Exception arg) when (arg.IsIllegalArgumentException()) { // pass } @@ -132,9 +128,7 @@ public virtual void TestExceptions() { new VirtualMethod(typeof(TestClass2), "PublicTest", typeof(string)); } -#pragma warning disable 168 - catch (ArgumentException arg) -#pragma warning restore 168 + catch (Exception arg) when (arg.IsIllegalArgumentException()) { Assert.Fail("Method publicTest(String) is declared in TestClass2, so IAE should not be thrown"); } @@ -145,9 +139,7 @@ public virtual void TestExceptions() new VirtualMethod(typeof(BaseTestVirtualMethod), "PublicTest", typeof(string)); Assert.Fail("Violating singleton status succeeded"); } -#pragma warning disable 168 - catch (ArgumentException arg) -#pragma warning restore 168 + catch (Exception arg) when (arg.IsUnsupportedOperationException()) { // pass } diff --git a/src/Lucene.Net.Tests/Util/TestWeakIdentityMap.cs b/src/Lucene.Net.Tests/Util/TestWeakIdentityMap.cs index 9ee0d8b920..0fd57a1864 100644 --- a/src/Lucene.Net.Tests/Util/TestWeakIdentityMap.cs +++ b/src/Lucene.Net.Tests/Util/TestWeakIdentityMap.cs @@ -158,9 +158,8 @@ // Assert.IsTrue(c >= newSize, "iteratorSize(" + c + ")>=newSize(" + newSize + ")"); // size = newSize; // } -// catch (ThreadInterruptedException) +// catch (Exception ie) when (ie.IsInterruptedException()) // { -// //LUCENENET NOTE: If this class is ever uncommented and used, think through weather we really want to be swallowing the exception here. // } // } @@ -268,9 +267,8 @@ // Assert.IsTrue(c >= newSize, "iteratorSize(" + c + ")>=newSize(" + newSize + ")"); // size = newSize; // } -// catch (ThreadInterruptedException) +// catch (Exception ie) when (ie.IsInterruptedException()) // { -// //LUCENENET NOTE: If this class is ever uncommented and used, think through weather we really want to be swallowing the exception here. // } // } // } diff --git a/src/Lucene.Net/Analysis/Analyzer.cs b/src/Lucene.Net/Analysis/Analyzer.cs index 5a1490be4c..ca455926fc 100644 --- a/src/Lucene.Net/Analysis/Analyzer.cs +++ b/src/Lucene.Net/Analysis/Analyzer.cs @@ -611,7 +611,7 @@ protected internal static object GetStoredValue(Analyzer analyzer) // LUCENENET: { if (analyzer.storedValue == null) { - throw new ObjectDisposedException(analyzer.GetType().FullName, "this Analyzer is closed"); + throw AlreadyClosedException.Create(analyzer.GetType().FullName, "this Analyzer is disposed."); } return analyzer.storedValue.Value; } @@ -626,7 +626,7 @@ protected internal static void SetStoredValue(Analyzer analyzer, object storedVa { if (analyzer.storedValue == null) { - throw new ObjectDisposedException(analyzer.GetType().FullName, "this Analyzer is closed"); + throw AlreadyClosedException.Create(analyzer.GetType().FullName, "this Analyzer is disposed."); } analyzer.storedValue.Value = storedValue; } diff --git a/src/Lucene.Net/Analysis/CharFilter.cs b/src/Lucene.Net/Analysis/CharFilter.cs index 90d1cf9771..9b08bb282b 100644 --- a/src/Lucene.Net/Analysis/CharFilter.cs +++ b/src/Lucene.Net/Analysis/CharFilter.cs @@ -110,7 +110,7 @@ public override int Read() /// The number of characters actually skipped public virtual long Skip(int n) { - throw new NotSupportedException("Skip() not supported"); + throw UnsupportedOperationException.Create("Skip() not supported"); } /// @@ -119,7 +119,7 @@ public virtual long Skip(int n) /// public virtual void Reset() { - throw new NotSupportedException("Reset() not supported"); + throw UnsupportedOperationException.Create("Reset() not supported"); } /// diff --git a/src/Lucene.Net/Analysis/NumericTokenStream.cs b/src/Lucene.Net/Analysis/NumericTokenStream.cs index 67a3671d66..290e18ab52 100644 --- a/src/Lucene.Net/Analysis/NumericTokenStream.cs +++ b/src/Lucene.Net/Analysis/NumericTokenStream.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Analysis.TokenAttributes; +using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Diagnostics; using Lucene.Net.Util; using System; @@ -265,7 +265,7 @@ public NumericTokenStream(AttributeSource.AttributeFactory factory, int precisio InitializeInstanceFields(); if (precisionStep < 1) { - throw new ArgumentException("precisionStep must be >=1"); + throw new ArgumentOutOfRangeException(nameof(precisionStep), "precisionStep must be >=1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.precisionStep = precisionStep; numericAtt.Shift = -precisionStep; @@ -328,7 +328,7 @@ public override void Reset() { if (valSize == 0) { - throw new Exception("call Set???Value() before usage"); + throw IllegalStateException.Create("call Set???Value() before usage"); } numericAtt.Shift = -precisionStep; } @@ -337,7 +337,7 @@ public override bool IncrementToken() { if (valSize == 0) { - throw new Exception("call Set???Value() before usage"); + throw IllegalStateException.Create("call Set???Value() before usage"); } // this will only clear all other attributes in this TokenStream diff --git a/src/Lucene.Net/Analysis/Token.cs b/src/Lucene.Net/Analysis/Token.cs index 42da6f9cee..539bc25859 100644 --- a/src/Lucene.Net/Analysis/Token.cs +++ b/src/Lucene.Net/Analysis/Token.cs @@ -1,4 +1,4 @@ -using J2N.Text; +using J2N.Text; using Lucene.Net.Analysis.TokenAttributes; using System; using System.Reflection; @@ -257,7 +257,7 @@ public virtual int PositionIncrement { if (value < 0) { - throw new ArgumentException("Increment must be zero or greater: " + value); + throw new ArgumentOutOfRangeException(nameof(PositionIncrement), "Increment must be zero or greater: " + value); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.positionIncrement = value; } diff --git a/src/Lucene.Net/Analysis/TokenAttributes/PositionIncrementAttribute.cs b/src/Lucene.Net/Analysis/TokenAttributes/PositionIncrementAttribute.cs index 7a737e5946..952db5c377 100644 --- a/src/Lucene.Net/Analysis/TokenAttributes/PositionIncrementAttribute.cs +++ b/src/Lucene.Net/Analysis/TokenAttributes/PositionIncrementAttribute.cs @@ -41,7 +41,7 @@ public virtual int PositionIncrement { if (value < 0) { - throw new ArgumentException("Increment must be zero or greater: got " + value); + throw new ArgumentOutOfRangeException(nameof(PositionIncrement), "Increment must be zero or greater: got " + value); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.positionIncrement = value; } diff --git a/src/Lucene.Net/Analysis/TokenAttributes/PositionLengthAttribute.cs b/src/Lucene.Net/Analysis/TokenAttributes/PositionLengthAttribute.cs index a26e3b182a..4ee38275c9 100644 --- a/src/Lucene.Net/Analysis/TokenAttributes/PositionLengthAttribute.cs +++ b/src/Lucene.Net/Analysis/TokenAttributes/PositionLengthAttribute.cs @@ -41,7 +41,7 @@ public virtual int PositionLength { if (value < 1) { - throw new ArgumentException("Position length must be 1 or greater: got " + value); + throw new ArgumentOutOfRangeException(nameof(PositionLength), "Position length must be 1 or greater: got " + value); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.positionLength = value; } diff --git a/src/Lucene.Net/Analysis/Tokenizer.cs b/src/Lucene.Net/Analysis/Tokenizer.cs index 3b4c37e129..d8f889725b 100644 --- a/src/Lucene.Net/Analysis/Tokenizer.cs +++ b/src/Lucene.Net/Analysis/Tokenizer.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.IO; @@ -44,7 +44,7 @@ public abstract class Tokenizer : TokenStream /// Construct a token stream processing the given input. protected internal Tokenizer(TextReader input) { - this.inputPending = input ?? throw new ArgumentNullException(nameof(input), "input must not be null"); + this.inputPending = input ?? throw new ArgumentNullException(nameof(input), "input must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -53,7 +53,7 @@ protected internal Tokenizer(TextReader input) protected internal Tokenizer(AttributeFactory factory, TextReader input) : base(factory) { - this.inputPending = input ?? throw new ArgumentNullException(nameof(input), "input must not be null"); + this.inputPending = input ?? throw new ArgumentNullException(nameof(input), "input must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -99,13 +99,13 @@ protected internal int CorrectOffset(int currentOff) /// public void SetReader(TextReader input) { - if (input == null) + if (input is null) { - throw new ArgumentNullException("value", "input must not be null"); + throw new ArgumentNullException(nameof(input), "input must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } else if (this.m_input != ILLEGAL_STATE_READER) { - throw new InvalidOperationException("TokenStream contract violation: Close() call missing"); + throw IllegalStateException.Create("TokenStream contract violation: Close() call missing"); } this.inputPending = input; if (Debugging.AssertsEnabled) Debugging.Assert(SetReaderTestPoint()); @@ -130,7 +130,7 @@ private class ReaderAnonymousClass : TextReader { public override int Read(char[] cbuf, int off, int len) { - throw new InvalidOperationException("TokenStream contract violation: Reset()/Dispose() call missing, " + throw IllegalStateException.Create("TokenStream contract violation: Reset()/Dispose() call missing, " + "Reset() called multiple times, or subclass does not call base.Reset(). " + "Please see the documentation of TokenStream class for more information about the correct consuming workflow."); } diff --git a/src/Lucene.Net/Codecs/BlockTreeTermsReader.cs b/src/Lucene.Net/Codecs/BlockTreeTermsReader.cs index 036ecc3c2a..d0025cd77d 100644 --- a/src/Lucene.Net/Codecs/BlockTreeTermsReader.cs +++ b/src/Lucene.Net/Codecs/BlockTreeTermsReader.cs @@ -310,7 +310,7 @@ internal virtual string BrToString(BytesRef b) { return b.Utf8ToString() + " " + b; } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // If BytesRef isn't actually UTF8, or it's eg a // prefix of UTF8 that ends mid-unicode-char, we @@ -472,7 +472,7 @@ internal virtual void EndBlock(FieldReader.SegmentTermsEnum.Frame frame) } else { - throw new InvalidOperationException(); + throw IllegalStateException.Create(); } endBlockCount++; long otherBytes = frame.fpEnd - frame.fp - frame.suffixesReader.Length - frame.statsReader.Length; @@ -637,7 +637,7 @@ public override TermsEnum Intersect(CompiledAutomaton compiled, BytesRef startTe { if (compiled.Type != CompiledAutomaton.AUTOMATON_TYPE.NORMAL) { - throw new ArgumentException("please use CompiledAutomaton.getTermsEnum instead"); + throw new ArgumentException("please use CompiledAutomaton.GetTermsEnum() instead"); } return new IntersectEnum(this, compiled, startTerm); } @@ -1472,19 +1472,19 @@ internal void CopyTerm() public override bool SeekExact(BytesRef text) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); public override SeekStatus SeekCeil(BytesRef text) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } @@ -1797,7 +1797,7 @@ public override bool SeekExact(BytesRef target) { if (outerInstance.index == null) { - throw new InvalidOperationException("terms index was not loaded"); + throw IllegalStateException.Create("terms index was not loaded"); } if (term.Bytes.Length <= target.Length) @@ -2084,7 +2084,7 @@ public override SeekStatus SeekCeil(BytesRef target) { if (outerInstance.index == null) { - throw new InvalidOperationException("terms index was not loaded"); + throw IllegalStateException.Create("terms index was not loaded"); } if (term.Bytes.Length <= target.Length) @@ -2582,10 +2582,10 @@ public override TermState GetTermState() public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); // Not static -- references term, postingsReader, // fieldInfo, in diff --git a/src/Lucene.Net/Codecs/BlockTreeTermsWriter.cs b/src/Lucene.Net/Codecs/BlockTreeTermsWriter.cs index 342bbdddf8..7cb6381a73 100644 --- a/src/Lucene.Net/Codecs/BlockTreeTermsWriter.cs +++ b/src/Lucene.Net/Codecs/BlockTreeTermsWriter.cs @@ -287,11 +287,11 @@ public BlockTreeTermsWriter(SegmentWriteState state, PostingsWriterBase postings { if (minItemsInBlock <= 1) { - throw new ArgumentException("minItemsInBlock must be >= 2; got " + minItemsInBlock); + throw new ArgumentOutOfRangeException(nameof(minItemsInBlock), "minItemsInBlock must be >= 2; got " + minItemsInBlock); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (maxItemsInBlock <= 0) { - throw new ArgumentException("maxItemsInBlock must be >= 1; got " + maxItemsInBlock); + throw new ArgumentOutOfRangeException(nameof(maxItemsInBlock), "maxItemsInBlock must be >= 1; got " + maxItemsInBlock); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (minItemsInBlock > maxItemsInBlock) { @@ -941,7 +941,7 @@ private string ToString(BytesRef b) { return b.Utf8ToString() + " " + b; } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // If BytesRef isn't actually UTF8, or it's eg a // prefix of UTF8 that ends mid-unicode-char, we @@ -1283,7 +1283,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - IOException ioe = null; + Exception ioe = null; // LUCENENET: No need to cast to IOExcpetion try { long dirStart = @out.GetFilePointer(); @@ -1312,7 +1312,7 @@ protected override void Dispose(bool disposing) WriteIndexTrailer(indexOut, indexDirStart); CodecUtil.WriteFooter(indexOut); } - catch (IOException ioe2) + catch (Exception ioe2) when (ioe2.IsIOException()) { ioe = ioe2; } diff --git a/src/Lucene.Net/Codecs/Codec.cs b/src/Lucene.Net/Codecs/Codec.cs index 1a26fefee3..6ec8c00746 100644 --- a/src/Lucene.Net/Codecs/Codec.cs +++ b/src/Lucene.Net/Codecs/Codec.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Util; +using Lucene.Net.Util; using System; using System.Collections.Generic; @@ -150,7 +150,7 @@ public static ICollection AvailableCodecs } else { - throw new NotSupportedException("The current CodecFactory class does not implement IServiceListable."); + throw UnsupportedOperationException.Create("The current CodecFactory class does not implement IServiceListable."); } } } diff --git a/src/Lucene.Net/Codecs/CodecUtil.cs b/src/Lucene.Net/Codecs/CodecUtil.cs index 7bbdaa44b5..6685287ed3 100644 --- a/src/Lucene.Net/Codecs/CodecUtil.cs +++ b/src/Lucene.Net/Codecs/CodecUtil.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Store; using Lucene.Net.Util; using System; diff --git a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsFormat.cs b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsFormat.cs index 487cb5523a..acb921f278 100644 --- a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsFormat.cs +++ b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsFormat.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.CompilerServices; namespace Lucene.Net.Codecs.Compressing @@ -97,7 +97,7 @@ public CompressingStoredFieldsFormat(string formatName, string segmentSuffix, Co this.compressionMode = compressionMode; if (chunkSize < 1) { - throw new ArgumentException("chunkSize must be >= 1"); + throw new ArgumentOutOfRangeException(nameof(chunkSize), "chunkSize must be >= 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.chunkSize = chunkSize; } diff --git a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsIndexReader.cs b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsIndexReader.cs index 9db213e6ba..791b9d666c 100644 --- a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsIndexReader.cs +++ b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsIndexReader.cs @@ -180,7 +180,7 @@ internal long GetStartPointer(int docID) { if (docID < 0 || docID >= maxDoc) { - throw new ArgumentException("docID out of range [0-" + maxDoc + "]: " + docID); + throw new ArgumentOutOfRangeException(nameof(docID), "docID out of range [0-" + maxDoc + "]: " + docID); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } int block = Block(docID); int relativeChunk = RelativeChunk(block, docID - docBases[block]); diff --git a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsIndexWriter.cs b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsIndexWriter.cs index c57cf33f8f..95022efdf9 100644 --- a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsIndexWriter.cs +++ b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsIndexWriter.cs @@ -214,7 +214,7 @@ internal void Finish(int numDocs, long maxPointer) { if (numDocs != totalDocs) { - throw new InvalidOperationException("Expected " + numDocs + " docs, but got " + totalDocs); + throw IllegalStateException.Create("Expected " + numDocs + " docs, but got " + totalDocs); } if (blockChunks > 0) { diff --git a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsReader.cs b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsReader.cs index bfc095d35e..24d793206a 100644 --- a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsReader.cs +++ b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsReader.cs @@ -3,6 +3,7 @@ using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; +using System.IO; using System.Runtime.CompilerServices; namespace Lucene.Net.Codecs.Compressing @@ -173,7 +174,7 @@ private void EnsureOpen() { if (closed) { - throw new ObjectDisposedException(this.GetType().FullName, "this FieldsReader is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this FieldsReader is disposed."); } } @@ -227,7 +228,7 @@ private static void ReadField(DataInput @in, StoredFieldVisitor visitor, FieldIn break; default: - throw new InvalidOperationException("Unknown type flag: " + bits.ToString("x")); + throw AssertionError.Create("Unknown type flag: " + bits.ToString("x")); } } @@ -252,7 +253,7 @@ private static void SkipField(DataInput @in, int bits) break; default: - throw new InvalidOperationException("Unknown type flag: " + bits.ToString("x")); + throw AssertionError.Create("Unknown type flag: " + bits.ToString("x")); } } @@ -399,7 +400,7 @@ internal virtual void FillBuffer() if (Debugging.AssertsEnabled) Debugging.Assert(decompressed <= length); if (decompressed == length) { - throw new Exception(); + throw EOFException.Create(); } int toDecompress = Math.Min(length - decompressed, outerInstance.chunkSize); outerInstance.decompressor.Decompress(outerInstance.fieldsStream, toDecompress, 0, toDecompress, outerInstance.bytes); diff --git a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsWriter.cs b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsWriter.cs index 8cc1dd6dfa..f247dfa946 100644 --- a/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsWriter.cs +++ b/src/Lucene.Net/Codecs/Compressing/CompressingStoredFieldsWriter.cs @@ -1,4 +1,4 @@ -using J2N; +using J2N; using Lucene.Net.Codecs.Lucene40; using Lucene.Net.Diagnostics; using Lucene.Net.Documents; @@ -358,7 +358,7 @@ public override void WriteField(FieldInfo info, IIndexableField field) bufferedDocs.WriteInt64(BitConversion.DoubleToInt64Bits(field.GetDoubleValue().Value)); break; default: - throw new Exception("Cannot get here"); + throw AssertionError.Create("Cannot get here"); } } } @@ -382,7 +382,7 @@ public override void Finish(FieldInfos fis, int numDocs) } if (docBase != numDocs) { - throw new Exception("Wrote " + docBase + " docs, finish called with numDocs=" + numDocs); + throw RuntimeException.Create("Wrote " + docBase + " docs, finish called with numDocs=" + numDocs); } indexWriter.Finish(numDocs, fieldsStream.GetFilePointer()); CodecUtil.WriteFooter(fieldsStream); diff --git a/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsFormat.cs b/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsFormat.cs index e01c3f04ea..8d24c6b229 100644 --- a/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsFormat.cs +++ b/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsFormat.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.CompilerServices; using Directory = Lucene.Net.Store.Directory; @@ -70,7 +70,7 @@ public CompressingTermVectorsFormat(string formatName, string segmentSuffix, Com this.compressionMode = compressionMode; if (chunkSize < 1) { - throw new ArgumentException("chunkSize must be >= 1"); + throw new ArgumentOutOfRangeException(nameof(chunkSize), "chunkSize must be >= 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.chunkSize = chunkSize; } diff --git a/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsReader.cs b/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsReader.cs index c3ccdd06f0..854e0e1401 100644 --- a/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsReader.cs +++ b/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsReader.cs @@ -106,7 +106,7 @@ public CompressingTermVectorsReader(Directory d, SegmentInfo si, string segmentS int version2 = CodecUtil.CheckHeader(vectorsStream, codecNameDat, CompressingTermVectorsWriter.VERSION_START, CompressingTermVectorsWriter.VERSION_CURRENT); if (version != version2) { - throw new Exception("Version mismatch between stored fields index and data: " + version + " != " + version2); + throw RuntimeException.Create("Version mismatch between stored fields index and data: " + version + " != " + version2); } if (Debugging.AssertsEnabled) Debugging.Assert(CodecUtil.HeaderLength(codecNameDat) == vectorsStream.GetFilePointer()); @@ -147,7 +147,7 @@ private void EnsureOpen() { if (closed) { - throw new ObjectDisposedException(this.GetType().FullName, "this FieldsReader is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this FieldsReader is disposed."); } } @@ -265,7 +265,7 @@ public override Fields Get(int doc) break; default: - throw new Exception(); + throw AssertionError.Create(); } for (int i = 0; i < numFields; ++i) { @@ -910,12 +910,12 @@ public override TermsEnum.SeekStatus SeekCeil(BytesRef text) public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override BytesRef Term => term; - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); public override int DocFreq => 1; @@ -983,11 +983,11 @@ private void CheckDoc() { if (doc == NO_MORE_DOCS) { - throw new InvalidOperationException("DocsEnum exhausted"); + throw IllegalStateException.Create("DocsEnum exhausted"); } else if (doc == -1) { - throw new InvalidOperationException("DocsEnum not started"); + throw IllegalStateException.Create("DocsEnum not started"); } } @@ -997,11 +997,11 @@ private void CheckPosition() CheckDoc(); if (i < 0) { - throw new InvalidOperationException("Position enum not started"); + throw IllegalStateException.Create("Position enum not started"); } else if (i >= termFreq) { - throw new InvalidOperationException("Read past last position"); + throw IllegalStateException.Create("Read past last position"); } } @@ -1009,11 +1009,11 @@ public override int NextPosition() { if (doc != 0) { - throw new InvalidOperationException(); + throw IllegalStateException.Create(); } else if (i >= termFreq - 1) { - throw new InvalidOperationException("Read past last position"); + throw IllegalStateException.Create("Read past last position"); } ++i; diff --git a/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsWriter.cs b/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsWriter.cs index f4b612f676..f2a5592ac7 100644 --- a/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsWriter.cs +++ b/src/Lucene.Net/Codecs/Compressing/CompressingTermVectorsWriter.cs @@ -799,7 +799,7 @@ public override void Finish(FieldInfos fis, int numDocs) } if (numDocs != this.numDocs) { - throw new Exception("Wrote " + this.numDocs + " docs, finish called with numDocs=" + numDocs); + throw RuntimeException.Create("Wrote " + this.numDocs + " docs, finish called with numDocs=" + numDocs); } indexWriter.Finish(numDocs, vectorsStream.GetFilePointer()); CodecUtil.WriteFooter(vectorsStream); diff --git a/src/Lucene.Net/Codecs/DocValuesFormat.cs b/src/Lucene.Net/Codecs/DocValuesFormat.cs index 919855af4b..5fc1993e09 100644 --- a/src/Lucene.Net/Codecs/DocValuesFormat.cs +++ b/src/Lucene.Net/Codecs/DocValuesFormat.cs @@ -158,7 +158,7 @@ public static ICollection AvailableDocValuesFormats } else { - throw new NotSupportedException("The current DocValuesFormatFactory class does not implement IServiceListable."); + throw UnsupportedOperationException.Create("The current DocValuesFormatFactory class does not implement IServiceListable."); } } } diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xCodec.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xCodec.cs index c93d02cc54..d0e4fb4560 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xCodec.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xCodec.cs @@ -69,7 +69,7 @@ public DocValuesFormatAnonymousClass() public override DocValuesConsumer FieldsConsumer(SegmentWriteState state) { - throw new NotSupportedException("this codec cannot write docvalues"); + throw UnsupportedOperationException.Create("this codec cannot write docvalues"); } public override DocValuesProducer FieldsProducer(SegmentReadState state) diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xFieldInfosFormat.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xFieldInfosFormat.cs index 417eb3268e..6cf3a7d721 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xFieldInfosFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xFieldInfosFormat.cs @@ -31,6 +31,6 @@ internal class Lucene3xFieldInfosFormat : FieldInfosFormat public override FieldInfosReader FieldInfosReader => reader; - public override FieldInfosWriter FieldInfosWriter => throw new NotSupportedException("this codec can only be used for reading"); + public override FieldInfosWriter FieldInfosWriter => throw UnsupportedOperationException.Create("this codec can only be used for reading"); } } \ No newline at end of file diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xFields.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xFields.cs index dc0d5b3a0b..385a1c72a5 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xFields.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xFields.cs @@ -817,10 +817,10 @@ public override IComparer Comparer public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); public override SeekStatus SeekCeil(BytesRef term) { diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xNormsFormat.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xNormsFormat.cs index 58432c7777..ccca329394 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xNormsFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xNormsFormat.cs @@ -33,7 +33,7 @@ internal class Lucene3xNormsFormat : NormsFormat { public override DocValuesConsumer NormsConsumer(SegmentWriteState state) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xNormsProducer.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xNormsProducer.cs index 2f55ce08b3..b5e4792f1d 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xNormsProducer.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xNormsProducer.cs @@ -1,4 +1,4 @@ -using J2N.Runtime.CompilerServices; +using J2N.Runtime.CompilerServices; using J2N.Threading.Atomic; using Lucene.Net.Diagnostics; using System; @@ -269,22 +269,22 @@ public override NumericDocValues GetNumeric(FieldInfo field) public override BinaryDocValues GetBinary(FieldInfo field) { - throw new InvalidOperationException(); + throw AssertionError.Create(); } public override SortedDocValues GetSorted(FieldInfo field) { - throw new InvalidOperationException(); + throw AssertionError.Create(); } public override SortedSetDocValues GetSortedSet(FieldInfo field) { - throw new InvalidOperationException(); + throw AssertionError.Create(); } public override IBits GetDocsWithField(FieldInfo field) { - throw new InvalidOperationException(); + throw AssertionError.Create(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xPostingsFormat.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xPostingsFormat.cs index 40c204b7b8..238e2f5ece 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xPostingsFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xPostingsFormat.cs @@ -56,7 +56,7 @@ public Lucene3xPostingsFormat() public override FieldsConsumer FieldsConsumer(SegmentWriteState state) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xSegmentInfoFormat.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xSegmentInfoFormat.cs index b3dbf877cf..a1d38258e6 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xSegmentInfoFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xSegmentInfoFormat.cs @@ -59,7 +59,7 @@ public class Lucene3xSegmentInfoFormat : SegmentInfoFormat public override SegmentInfoReader SegmentInfoReader => reader; - public override SegmentInfoWriter SegmentInfoWriter => throw new NotSupportedException("this codec can only be used for reading"); + public override SegmentInfoWriter SegmentInfoWriter => throw UnsupportedOperationException.Create("this codec can only be used for reading"); // only for backwards compat public static readonly string DS_OFFSET_KEY = typeof(Lucene3xSegmentInfoFormat).Name + ".dsoffset"; diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xStoredFieldsFormat.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xStoredFieldsFormat.cs index ef3d6fc663..1653119c2f 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xStoredFieldsFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xStoredFieldsFormat.cs @@ -36,7 +36,7 @@ public override StoredFieldsReader FieldsReader(Directory directory, SegmentInfo public override StoredFieldsWriter FieldsWriter(Directory directory, SegmentInfo si, IOContext context) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } } } \ No newline at end of file diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xStoredFieldsReader.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xStoredFieldsReader.cs index 1fd83ef467..62cc2619b3 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xStoredFieldsReader.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xStoredFieldsReader.cs @@ -224,7 +224,7 @@ public Lucene3xStoredFieldsReader(Directory d, SegmentInfo si, FieldInfos fn, IO { Dispose(); } // keep our original exception - catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception t) when (t.IsThrowable()) { // ignored } @@ -238,7 +238,7 @@ private void EnsureOpen() { if (closed) { - throw new ObjectDisposedException(this.GetType().FullName, "this FieldsReader is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this FieldsReader is disposed."); } } diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xTermVectorsFormat.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xTermVectorsFormat.cs index 6f4ddbbd3e..49f8ff0876 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xTermVectorsFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xTermVectorsFormat.cs @@ -83,7 +83,7 @@ public override TermVectorsReader VectorsReader(Directory directory, SegmentInfo public override TermVectorsWriter VectorsWriter(Directory directory, SegmentInfo segmentInfo, IOContext context) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } } } \ No newline at end of file diff --git a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xTermVectorsReader.cs b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xTermVectorsReader.cs index 254102272c..65ddaa6459 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/Lucene3xTermVectorsReader.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/Lucene3xTermVectorsReader.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using System; using System.Collections; @@ -184,7 +184,7 @@ public Lucene3xTermVectorsReader(Directory d, SegmentInfo si, FieldInfos fieldIn { Dispose(); } // keep our original exception - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { } } @@ -311,7 +311,7 @@ public bool MoveNext() public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public void Dispose() @@ -554,7 +554,7 @@ public override SeekStatus SeekCeil(BytesRef text) public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -577,7 +577,7 @@ public override BytesRef Next() public override BytesRef Term => termAndPostings[currentTerm].Term; - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); public override int DocFreq => 1; @@ -767,7 +767,7 @@ public override int NextPosition() // IndexOutOfRangeException if we didn't, which doesn't really provide good feedback as to what the cause is. // This matches the behavior of Lucene 8.x. See #267. if (((positions != null && nextPos < positions.Length) || startOffsets != null && nextPos < startOffsets.Length) == false) - throw new InvalidOperationException("Read past last position"); + throw IllegalStateException.Create("Read past last position"); if (positions != null) { diff --git a/src/Lucene.Net/Codecs/Lucene3x/SegmentTermPositions.cs b/src/Lucene.Net/Codecs/Lucene3x/SegmentTermPositions.cs index 9515d7dedc..680a486798 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/SegmentTermPositions.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/SegmentTermPositions.cs @@ -150,7 +150,7 @@ public sealed override bool Next() public sealed override int Read(int[] docs, int[] freqs) { - throw new NotSupportedException("TermPositions does not support processing multiple documents in one call. Use TermDocs instead."); + throw UnsupportedOperationException.Create("TermPositions does not support processing multiple documents in one call. Use TermDocs instead."); } /// diff --git a/src/Lucene.Net/Codecs/Lucene3x/TermInfosReader.cs b/src/Lucene.Net/Codecs/Lucene3x/TermInfosReader.cs index fc0d201365..f920ca611d 100644 --- a/src/Lucene.Net/Codecs/Lucene3x/TermInfosReader.cs +++ b/src/Lucene.Net/Codecs/Lucene3x/TermInfosReader.cs @@ -384,7 +384,7 @@ private void EnsureIndexIsRead() { if (index == null) { - throw new InvalidOperationException("terms index was not loaded when this reader was created"); + throw IllegalStateException.Create("terms index was not loaded when this reader was created"); } } diff --git a/src/Lucene.Net/Codecs/Lucene40/Lucene40DocValuesFormat.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40DocValuesFormat.cs index a56cc199e9..5a537522c2 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40DocValuesFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40DocValuesFormat.cs @@ -137,7 +137,7 @@ public Lucene40DocValuesFormat() public override DocValuesConsumer FieldsConsumer(SegmentWriteState state) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/Lucene.Net/Codecs/Lucene40/Lucene40DocValuesReader.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40DocValuesReader.cs index 038a5695b3..55b1a7a741 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40DocValuesReader.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40DocValuesReader.cs @@ -1,4 +1,5 @@ -using J2N.Threading.Atomic; +using J2N.Threading.Atomic; +using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Globalization; @@ -116,7 +117,7 @@ public override NumericDocValues GetNumeric(FieldInfo field) } else { - throw new InvalidOperationException(); + throw AssertionError.Create(); } CodecUtil.CheckEOF(input); @@ -454,7 +455,7 @@ public override BinaryDocValues GetBinary(FieldInfo field) } else { - throw new InvalidOperationException(); + throw AssertionError.Create(); } binaryInstances[field.Number] = instance; } @@ -724,7 +725,7 @@ public override SortedDocValues GetSorted(FieldInfo field) } else { - throw new InvalidOperationException(); + throw AssertionError.Create(); } CodecUtil.CheckEOF(data); @@ -887,7 +888,7 @@ public override void LookupOrd(int ord, BytesRef result) public override SortedSetDocValues GetSortedSet(FieldInfo field) { - throw new InvalidOperationException("Lucene 4.0 does not support SortedSet: how did you pull this off?"); + throw IllegalStateException.Create("Lucene 4.0 does not support SortedSet: how did you pull this off?"); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/Lucene.Net/Codecs/Lucene40/Lucene40FieldInfosFormat.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40FieldInfosFormat.cs index 28681a6165..e99e23d9f6 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40FieldInfosFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40FieldInfosFormat.cs @@ -100,7 +100,7 @@ public Lucene40FieldInfosFormat() public override FieldInfosReader FieldInfosReader => reader; - public override FieldInfosWriter FieldInfosWriter => throw new NotSupportedException("this codec can only be used for reading"); + public override FieldInfosWriter FieldInfosWriter => throw UnsupportedOperationException.Create("this codec can only be used for reading"); /// /// Extension of field infos diff --git a/src/Lucene.Net/Codecs/Lucene40/Lucene40NormsFormat.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40NormsFormat.cs index 2609d8abbf..c1e692b5c9 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40NormsFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40NormsFormat.cs @@ -49,7 +49,7 @@ public Lucene40NormsFormat() public override DocValuesConsumer NormsConsumer(SegmentWriteState state) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/Lucene.Net/Codecs/Lucene40/Lucene40PostingsBaseFormat.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40PostingsBaseFormat.cs index e6b887340d..5cc580ca66 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40PostingsBaseFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40PostingsBaseFormat.cs @@ -46,7 +46,7 @@ public override PostingsReaderBase PostingsReaderBase(SegmentReadState state) public override PostingsWriterBase PostingsWriterBase(SegmentWriteState state) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } } } \ No newline at end of file diff --git a/src/Lucene.Net/Codecs/Lucene40/Lucene40PostingsFormat.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40PostingsFormat.cs index 804b7d7bd2..5df448c578 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40PostingsFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40PostingsFormat.cs @@ -240,7 +240,7 @@ private Lucene40PostingsFormat(int minBlockSize, int maxBlockSize) public override FieldsConsumer FieldsConsumer(SegmentWriteState state) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } public override FieldsProducer FieldsProducer(SegmentReadState state) diff --git a/src/Lucene.Net/Codecs/Lucene40/Lucene40StoredFieldsReader.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40StoredFieldsReader.cs index 04fec9f335..a385f67aa9 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40StoredFieldsReader.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40StoredFieldsReader.cs @@ -121,7 +121,7 @@ public Lucene40StoredFieldsReader(Directory d, SegmentInfo si, FieldInfos fn, IO { Dispose(); } // ensure we throw our original exception - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { } } @@ -134,7 +134,7 @@ private void EnsureOpen() { if (closed) { - throw new ObjectDisposedException(this.GetType().FullName, "this FieldsReader is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this FieldsReader is disposed."); } } diff --git a/src/Lucene.Net/Codecs/Lucene40/Lucene40StoredFieldsWriter.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40StoredFieldsWriter.cs index 67e292f2b2..1506c4e709 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40StoredFieldsWriter.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40StoredFieldsWriter.cs @@ -154,7 +154,7 @@ public override void Abort() { Dispose(); } - catch (Exception) + catch (Exception ignored) when (ignored.IsThrowable()) { } IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, "", FIELDS_EXTENSION), IndexFileNames.SegmentFileName(segment, "", FIELDS_INDEX_EXTENSION)); @@ -247,7 +247,7 @@ public override void WriteField(FieldInfo info, IIndexableField field) fieldsStream.WriteInt64(BitConversion.DoubleToInt64Bits(field.GetDoubleValue().Value)); break; default: - throw new InvalidOperationException("Cannot get here"); + throw AssertionError.Create("Cannot get here"); } } } @@ -282,7 +282,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/Codecs/Lucene40/Lucene40TermVectorsReader.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40TermVectorsReader.cs index bdccfbbd59..5994411702 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40TermVectorsReader.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40TermVectorsReader.cs @@ -153,7 +153,7 @@ public Lucene40TermVectorsReader(Directory d, SegmentInfo si, FieldInfos fieldIn { Dispose(); } // ensure we throw our original exception - catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception t) when (t.IsThrowable()) { // ignored } @@ -473,7 +473,7 @@ public override SeekStatus SeekCeil(BytesRef text) public override void SeekExact(long ord) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override bool MoveNext() @@ -554,7 +554,7 @@ public override BytesRef Next() public override BytesRef Term => term; - public override long Ord => throw new NotSupportedException(); + public override long Ord => throw UnsupportedOperationException.Create(); public override int DocFreq => 1; @@ -732,7 +732,7 @@ public override int NextPosition() // IndexOutOfRangeException if we didn't, which doesn't really provide good feedback as to what the cause is. // This matches the behavior of Lucene 8.x. See #267. if (((positions != null && nextPos < positions.Length) || startOffsets != null && nextPos < startOffsets.Length) == false) - throw new InvalidOperationException("Read past last position"); + throw IllegalStateException.Create("Read past last position"); if (positions != null) { diff --git a/src/Lucene.Net/Codecs/Lucene40/Lucene40TermVectorsWriter.cs b/src/Lucene.Net/Codecs/Lucene40/Lucene40TermVectorsWriter.cs index 5c8875e214..49da6db833 100644 --- a/src/Lucene.Net/Codecs/Lucene40/Lucene40TermVectorsWriter.cs +++ b/src/Lucene.Net/Codecs/Lucene40/Lucene40TermVectorsWriter.cs @@ -317,7 +317,7 @@ private void WritePosition(int delta, BytesRef payload) { // we overflowed the payload buffer, just throw UOE // having > System.Int32.MaxValue bytes of payload for a single term in a single doc is nuts. - throw new NotSupportedException("A term cannot have more than System.Int32.MaxValue bytes of payload data in a single document"); + throw UnsupportedOperationException.Create("A term cannot have more than System.Int32.MaxValue bytes of payload data in a single document"); } payloadData.Append(payload); } @@ -335,9 +335,8 @@ public override void Abort() { Dispose(); } - catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception ignored) when (ignored.IsThrowable()) { - // ignored } IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_INDEX_EXTENSION), @@ -516,7 +515,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/Codecs/Lucene41/Lucene41Codec.cs b/src/Lucene.Net/Codecs/Lucene41/Lucene41Codec.cs index bafd126a63..193d31a28d 100644 --- a/src/Lucene.Net/Codecs/Lucene41/Lucene41Codec.cs +++ b/src/Lucene.Net/Codecs/Lucene41/Lucene41Codec.cs @@ -59,7 +59,7 @@ public CompressingStoredFieldsFormatAnonymousClass(string formatName, Compressio public override StoredFieldsWriter FieldsWriter(Directory directory, SegmentInfo si, IOContext context) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } } diff --git a/src/Lucene.Net/Codecs/Lucene41/Lucene41PostingsReader.cs b/src/Lucene.Net/Codecs/Lucene41/Lucene41PostingsReader.cs index 414bd3a6ef..33c4bbb129 100644 --- a/src/Lucene.Net/Codecs/Lucene41/Lucene41PostingsReader.cs +++ b/src/Lucene.Net/Codecs/Lucene41/Lucene41PostingsReader.cs @@ -94,7 +94,7 @@ public override void Init(IndexInput termsIn) int indexBlockSize = termsIn.ReadVInt32(); if (indexBlockSize != Lucene41PostingsFormat.BLOCK_SIZE) { - throw new InvalidOperationException("index-time BLOCK_SIZE (" + indexBlockSize + ") != read-time BLOCK_SIZE (" + Lucene41PostingsFormat.BLOCK_SIZE + ")"); + throw IllegalStateException.Create("index-time BLOCK_SIZE (" + indexBlockSize + ") != read-time BLOCK_SIZE (" + Lucene41PostingsFormat.BLOCK_SIZE + ")"); } } diff --git a/src/Lucene.Net/Codecs/Lucene41/Lucene41PostingsWriter.cs b/src/Lucene.Net/Codecs/Lucene41/Lucene41PostingsWriter.cs index a7ef3ab3b5..f788a42be5 100644 --- a/src/Lucene.Net/Codecs/Lucene41/Lucene41PostingsWriter.cs +++ b/src/Lucene.Net/Codecs/Lucene41/Lucene41PostingsWriter.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using System; using System.Runtime.CompilerServices; @@ -318,7 +318,7 @@ public override void StartDoc(int docId, int termDocFreq) if (docId < 0 || (docCount > 0 && docDelta <= 0)) { - throw new Exception("docs out of order (" + docId + " <= " + lastDocID + " ) (docOut: " + docOut + ")"); + throw new CorruptIndexException("docs out of order (" + docId + " <= " + lastDocID + " ) (docOut: " + docOut + ")"); } docDeltaBuffer[docBufferUpto] = docDelta; diff --git a/src/Lucene.Net/Codecs/Lucene42/Lucene42Codec.cs b/src/Lucene.Net/Codecs/Lucene42/Lucene42Codec.cs index 747b305255..4d5020df42 100644 --- a/src/Lucene.Net/Codecs/Lucene42/Lucene42Codec.cs +++ b/src/Lucene.Net/Codecs/Lucene42/Lucene42Codec.cs @@ -154,7 +154,7 @@ private class Lucene42NormsFormatAnonymousClass : Lucene42NormsFormat { public override DocValuesConsumer NormsConsumer(SegmentWriteState state) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } } diff --git a/src/Lucene.Net/Codecs/Lucene42/Lucene42DocValuesFormat.cs b/src/Lucene.Net/Codecs/Lucene42/Lucene42DocValuesFormat.cs index 005eb00f8d..eafdbf5c3d 100644 --- a/src/Lucene.Net/Codecs/Lucene42/Lucene42DocValuesFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene42/Lucene42DocValuesFormat.cs @@ -153,7 +153,7 @@ public Lucene42DocValuesFormat(float acceptableOverheadRatio) public override DocValuesConsumer FieldsConsumer(SegmentWriteState state) { - throw new NotSupportedException("this codec can only be used for reading"); + throw UnsupportedOperationException.Create("this codec can only be used for reading"); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/Lucene.Net/Codecs/Lucene42/Lucene42DocValuesProducer.cs b/src/Lucene.Net/Codecs/Lucene42/Lucene42DocValuesProducer.cs index 5b4e24be73..e7e85dd8c6 100644 --- a/src/Lucene.Net/Codecs/Lucene42/Lucene42DocValuesProducer.cs +++ b/src/Lucene.Net/Codecs/Lucene42/Lucene42DocValuesProducer.cs @@ -1,4 +1,4 @@ -using J2N.Threading.Atomic; +using J2N.Threading.Atomic; using Lucene.Net.Index; using Lucene.Net.Util.Fst; using System; @@ -288,7 +288,7 @@ private NumericDocValues LoadNumeric(FieldInfo field) return new NumericDocValuesAnonymousClass3(min, mult, quotientReader); default: - throw new InvalidOperationException(); + throw AssertionError.Create(); } } @@ -486,9 +486,9 @@ public override void LookupOrd(int ord, BytesRef result) result.Length = 0; Util.ToBytesRef(output, result); } - catch (IOException bogus) + catch (Exception bogus) when (bogus.IsIOException()) { - throw new Exception(bogus.ToString(), bogus); + throw RuntimeException.Create(bogus); } } @@ -510,9 +510,9 @@ public override int LookupTerm(BytesRef key) return (int)-o.Output.GetValueOrDefault() - 1; } } - catch (IOException bogus) + catch (Exception bogus) when (bogus.IsIOException()) { - throw new Exception(bogus.ToString(), bogus); + throw RuntimeException.Create(bogus); } } @@ -620,9 +620,9 @@ public override void LookupOrd(long ord, BytesRef result) result.Length = 0; Lucene.Net.Util.Fst.Util.ToBytesRef(output, result); } - catch (IOException bogus) + catch (Exception bogus) when (bogus.IsIOException()) { - throw new Exception(bogus.ToString(), bogus); + throw RuntimeException.Create(bogus); } } @@ -644,9 +644,9 @@ public override long LookupTerm(BytesRef key) return -o.Output.GetValueOrDefault() - 1; } } - catch (IOException bogus) + catch (Exception bogus) when (bogus.IsIOException()) { - throw new Exception(bogus.ToString(), bogus); + throw RuntimeException.Create(bogus); } } @@ -796,18 +796,18 @@ public override void SeekExact(long ord) public override long Ord => @in.Current.Output.GetValueOrDefault(); - public override int DocFreq => throw new NotSupportedException(); + public override int DocFreq => throw UnsupportedOperationException.Create(); - public override long TotalTermFreq => throw new NotSupportedException(); + public override long TotalTermFreq => throw UnsupportedOperationException.Create(); public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } diff --git a/src/Lucene.Net/Codecs/Lucene42/Lucene42FieldInfosFormat.cs b/src/Lucene.Net/Codecs/Lucene42/Lucene42FieldInfosFormat.cs index d961a561d0..e2f93a9300 100644 --- a/src/Lucene.Net/Codecs/Lucene42/Lucene42FieldInfosFormat.cs +++ b/src/Lucene.Net/Codecs/Lucene42/Lucene42FieldInfosFormat.cs @@ -90,7 +90,7 @@ public Lucene42FieldInfosFormat() public override FieldInfosReader FieldInfosReader => reader; - public override FieldInfosWriter FieldInfosWriter => throw new NotSupportedException("this codec can only be used for reading"); + public override FieldInfosWriter FieldInfosWriter => throw UnsupportedOperationException.Create("this codec can only be used for reading"); /// /// Extension of field infos. diff --git a/src/Lucene.Net/Codecs/Lucene42/Lucene42NormsConsumer.cs b/src/Lucene.Net/Codecs/Lucene42/Lucene42NormsConsumer.cs index b949414580..73e62e4285 100644 --- a/src/Lucene.Net/Codecs/Lucene42/Lucene42NormsConsumer.cs +++ b/src/Lucene.Net/Codecs/Lucene42/Lucene42NormsConsumer.cs @@ -235,17 +235,17 @@ protected override void Dispose(bool disposing) public override void AddBinaryField(FieldInfo field, IEnumerable values) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override void AddSortedField(FieldInfo field, IEnumerable values, IEnumerable docToOrd) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override void AddSortedSetField(FieldInfo field, IEnumerable values, IEnumerable docToOrdCount, IEnumerable ords) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } \ No newline at end of file diff --git a/src/Lucene.Net/Codecs/Lucene45/Lucene45DocValuesConsumer.cs b/src/Lucene.Net/Codecs/Lucene45/Lucene45DocValuesConsumer.cs index d26013f22c..f595ec2330 100644 --- a/src/Lucene.Net/Codecs/Lucene45/Lucene45DocValuesConsumer.cs +++ b/src/Lucene.Net/Codecs/Lucene45/Lucene45DocValuesConsumer.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Collections; using System.Collections.Generic; @@ -259,7 +259,7 @@ internal virtual void AddNumericField(FieldInfo field, IEnumerable values break; default: - throw new InvalidOperationException(); + throw AssertionError.Create(); } } diff --git a/src/Lucene.Net/Codecs/Lucene45/Lucene45DocValuesProducer.cs b/src/Lucene.Net/Codecs/Lucene45/Lucene45DocValuesProducer.cs index 2f4fb0a238..b13cabff89 100644 --- a/src/Lucene.Net/Codecs/Lucene45/Lucene45DocValuesProducer.cs +++ b/src/Lucene.Net/Codecs/Lucene45/Lucene45DocValuesProducer.cs @@ -1,5 +1,6 @@ using J2N.Numerics; using J2N.Threading.Atomic; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Util; using System; @@ -122,7 +123,7 @@ protected internal Lucene45DocValuesProducer(SegmentReadState state, string data int version2 = CodecUtil.CheckHeader(data, dataCodec, Lucene45DocValuesFormat.VERSION_START, Lucene45DocValuesFormat.VERSION_CURRENT); if (version != version2) { - throw new Exception("Format versions mismatch"); + throw new CorruptIndexException("Format versions mismatch"); } success = true; @@ -143,22 +144,22 @@ private void ReadSortedField(int fieldNumber, IndexInput meta /*, FieldInfos inf // sorted = binary + numeric if (meta.ReadVInt32() != fieldNumber) { - throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } if (meta.ReadByte() != Lucene45DocValuesFormat.BINARY) { - throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } BinaryEntry b = ReadBinaryEntry(meta); binaries[fieldNumber] = b; if (meta.ReadVInt32() != fieldNumber) { - throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } if (meta.ReadByte() != Lucene45DocValuesFormat.NUMERIC) { - throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } NumericEntry n = ReadNumericEntry(meta); ords[fieldNumber] = n; @@ -169,33 +170,33 @@ private void ReadSortedSetFieldWithAddresses(int fieldNumber, IndexInput meta /* // sortedset = binary + numeric (addresses) + ordIndex if (meta.ReadVInt32() != fieldNumber) { - throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } if (meta.ReadByte() != Lucene45DocValuesFormat.BINARY) { - throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } BinaryEntry b = ReadBinaryEntry(meta); binaries[fieldNumber] = b; if (meta.ReadVInt32() != fieldNumber) { - throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } if (meta.ReadByte() != Lucene45DocValuesFormat.NUMERIC) { - throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } NumericEntry n1 = ReadNumericEntry(meta); ords[fieldNumber] = n1; if (meta.ReadVInt32() != fieldNumber) { - throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } if (meta.ReadByte() != Lucene45DocValuesFormat.NUMERIC) { - throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } NumericEntry n2 = ReadNumericEntry(meta); ordIndexes[fieldNumber] = n2; @@ -212,7 +213,7 @@ private void ReadFields(IndexInput meta /*, FieldInfos infos // LUCENENET: Not r { // trickier to validate more: because we re-use for norms, because we use multiple entries // for "composite" types like sortedset, etc. - throw new Exception("Invalid field number: " + fieldNumber + " (resource=" + meta + ")"); + throw new CorruptIndexException("Invalid field number: " + fieldNumber + " (resource=" + meta + ")"); } byte type = meta.ReadByte(); if (type == Lucene45DocValuesFormat.NUMERIC) @@ -240,22 +241,22 @@ private void ReadFields(IndexInput meta /*, FieldInfos infos // LUCENENET: Not r { if (meta.ReadVInt32() != fieldNumber) { - throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } if (meta.ReadByte() != Lucene45DocValuesFormat.SORTED) { - throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); + throw new CorruptIndexException("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")"); } ReadSortedField(fieldNumber, meta/*, infos // LUCENENET: Never read */); } else { - throw new Exception(); + throw AssertionError.Create(); } } else { - throw new Exception("invalid type: " + type + ", resource=" + meta); + throw new CorruptIndexException("invalid type: " + type + ", resource=" + meta); } fieldNumber = meta.ReadVInt32(); } @@ -280,12 +281,12 @@ internal static NumericEntry ReadNumericEntry(IndexInput meta) case Lucene45DocValuesConsumer.TABLE_COMPRESSED: if (entry.Count > int.MaxValue) { - throw new Exception("Cannot use TABLE_COMPRESSED with more than MAX_VALUE values, input=" + meta); + throw new CorruptIndexException("Cannot use TABLE_COMPRESSED with more than MAX_VALUE values, input=" + meta); } int uniqueValues = meta.ReadVInt32(); if (uniqueValues > 256) { - throw new Exception("TABLE_COMPRESSED cannot have more than 256 distinct values, input=" + meta); + throw new CorruptIndexException("TABLE_COMPRESSED cannot have more than 256 distinct values, input=" + meta); } entry.table = new long[uniqueValues]; for (int i = 0; i < uniqueValues; ++i) @@ -298,7 +299,7 @@ internal static NumericEntry ReadNumericEntry(IndexInput meta) break; default: - throw new Exception("Unknown format: " + entry.format + ", input=" + meta); + throw new CorruptIndexException("Unknown format: " + entry.format + ", input=" + meta); } return entry; } @@ -331,7 +332,7 @@ internal static BinaryEntry ReadBinaryEntry(IndexInput meta) break; default: - throw new Exception("Unknown format: " + entry.format + ", input=" + meta); + throw new CorruptIndexException("Unknown format: " + entry.format + ", input=" + meta); } return entry; } @@ -349,7 +350,7 @@ internal virtual SortedSetEntry ReadSortedSetEntry(IndexInput meta) } if (entry.Format != Lucene45DocValuesConsumer.SORTED_SET_SINGLE_VALUED_SORTED && entry.Format != Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES) { - throw new Exception("Unknown format: " + entry.Format + ", input=" + meta); + throw new CorruptIndexException("Unknown format: " + entry.Format + ", input=" + meta); } return entry; } @@ -397,7 +398,7 @@ internal virtual Int64Values GetNumeric(NumericEntry entry) return new Int64ValuesAnonymousClass2(table, ords); default: - throw new Exception(); + throw AssertionError.Create(); } } @@ -454,7 +455,7 @@ public override BinaryDocValues GetBinary(FieldInfo field) return GetCompressedBinary(field, bytes); default: - throw new Exception(); + throw AssertionError.Create(); } } @@ -491,9 +492,9 @@ public override void Get(long id, BytesRef result) result.Offset = 0; result.Length = buffer.Length; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } @@ -559,9 +560,9 @@ public override void Get(long id, BytesRef result) result.Offset = 0; result.Length = length; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } @@ -706,7 +707,7 @@ public override SortedSetDocValues GetSortedSet(FieldInfo field) } else if (ss.Format != Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES) { - throw new Exception(); + throw AssertionError.Create(); } IndexInput data = (IndexInput)this.data.Clone(); @@ -843,9 +844,9 @@ public virtual bool Get(int index) @in.Seek(offset + (index >> 3)); return (@in.ReadByte() & (1 << (index & 7))) != 0; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } @@ -871,7 +872,7 @@ public override IBits GetDocsWithField(FieldInfo field) return GetMissingBits(ne.missingOffset); default: - throw new InvalidOperationException(); + throw AssertionError.Create(); } } @@ -1023,9 +1024,9 @@ public override void Get(long id, BytesRef result) result.Offset = term.Offset; result.Length = term.Length; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } @@ -1047,9 +1048,9 @@ internal virtual long LookupTerm(BytesRef key) return -termsEnum.Ord - 1; } } - catch (IOException bogus) + catch (Exception bogus) when (bogus.IsIOException()) { - throw new Exception(bogus.ToString(), bogus); + throw RuntimeException.Create(bogus); } } @@ -1060,9 +1061,9 @@ internal virtual TermsEnum GetTermsEnum() { return GetTermsEnum((IndexInput)data.Clone()); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } @@ -1221,18 +1222,18 @@ private void SetTerm() public override IComparer Comparer => BytesRef.UTF8SortedAsUnicodeComparer; - public override int DocFreq => throw new NotSupportedException(); + public override int DocFreq => throw UnsupportedOperationException.Create(); public override long TotalTermFreq => -1; public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } diff --git a/src/Lucene.Net/Codecs/Lucene46/Lucene46FieldInfosWriter.cs b/src/Lucene.Net/Codecs/Lucene46/Lucene46FieldInfosWriter.cs index c3e61de0e7..075e32fb86 100644 --- a/src/Lucene.Net/Codecs/Lucene46/Lucene46FieldInfosWriter.cs +++ b/src/Lucene.Net/Codecs/Lucene46/Lucene46FieldInfosWriter.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using System; using System.Diagnostics; @@ -142,7 +142,7 @@ private static sbyte DocValuesByte(DocValuesType type) } else { - throw new InvalidOperationException(); + throw AssertionError.Create(); } } } diff --git a/src/Lucene.Net/Codecs/MappingMultiDocsAndPositionsEnum.cs b/src/Lucene.Net/Codecs/MappingMultiDocsAndPositionsEnum.cs index fc5622c655..9c5ee8a10e 100644 --- a/src/Lucene.Net/Codecs/MappingMultiDocsAndPositionsEnum.cs +++ b/src/Lucene.Net/Codecs/MappingMultiDocsAndPositionsEnum.cs @@ -87,7 +87,7 @@ public MergeState MergeState public override int Advance(int target) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override int NextDoc() diff --git a/src/Lucene.Net/Codecs/MappingMultiDocsEnum.cs b/src/Lucene.Net/Codecs/MappingMultiDocsEnum.cs index 7a61290e2b..b933a495ec 100644 --- a/src/Lucene.Net/Codecs/MappingMultiDocsEnum.cs +++ b/src/Lucene.Net/Codecs/MappingMultiDocsEnum.cs @@ -86,7 +86,7 @@ public MergeState MergeState public override int Advance(int target) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override int NextDoc() diff --git a/src/Lucene.Net/Codecs/PerField/PerFieldDocValuesFormat.cs b/src/Lucene.Net/Codecs/PerField/PerFieldDocValuesFormat.cs index ddc3102173..818fe52c60 100644 --- a/src/Lucene.Net/Codecs/PerField/PerFieldDocValuesFormat.cs +++ b/src/Lucene.Net/Codecs/PerField/PerFieldDocValuesFormat.cs @@ -155,7 +155,7 @@ internal virtual DocValuesConsumer GetInstance(FieldInfo field) } if (format == null) { - throw new InvalidOperationException("invalid null DocValuesFormat for field=\"" + field.Name + "\""); + throw IllegalStateException.Create("invalid null DocValuesFormat for field=\"" + field.Name + "\""); } string formatName_ = format.Name; diff --git a/src/Lucene.Net/Codecs/PerField/PerFieldPostingsFormat.cs b/src/Lucene.Net/Codecs/PerField/PerFieldPostingsFormat.cs index def4773904..c16ef24ab2 100644 --- a/src/Lucene.Net/Codecs/PerField/PerFieldPostingsFormat.cs +++ b/src/Lucene.Net/Codecs/PerField/PerFieldPostingsFormat.cs @@ -113,7 +113,7 @@ public override TermsConsumer AddField(FieldInfo field) PostingsFormat format = outerInstance.GetPostingsFormatForField(field.Name); if (format == null) { - throw new InvalidOperationException("invalid null PostingsFormat for field=\"" + field.Name + "\""); + throw IllegalStateException.Create("invalid null PostingsFormat for field=\"" + field.Name + "\""); } string formatName = format.Name; @@ -192,7 +192,7 @@ internal static string GetFullSegmentSuffix(string fieldName, string outerSegmen // TODO: support embedding; I think it should work but // we need a test confirm to confirm // return outerSegmentSuffix + "_" + segmentSuffix; - throw new InvalidOperationException("cannot embed PerFieldPostingsFormat inside itself (field \"" + fieldName + "\" returned PerFieldPostingsFormat)"); + throw IllegalStateException.Create("cannot embed PerFieldPostingsFormat inside itself (field \"" + fieldName + "\" returned PerFieldPostingsFormat)"); } } diff --git a/src/Lucene.Net/Codecs/PostingsFormat.cs b/src/Lucene.Net/Codecs/PostingsFormat.cs index a315a2e133..4824deff7e 100644 --- a/src/Lucene.Net/Codecs/PostingsFormat.cs +++ b/src/Lucene.Net/Codecs/PostingsFormat.cs @@ -155,7 +155,7 @@ public static ICollection AvailablePostingsFormats } else { - throw new NotSupportedException("The current PostingsFormat factory class does not implement IServiceListable."); + throw UnsupportedOperationException.Create("The current PostingsFormat factory class does not implement IServiceListable."); } } } diff --git a/src/Lucene.Net/Document/DateTools.cs b/src/Lucene.Net/Document/DateTools.cs index 7dca3a8d7d..21b4fdc037 100644 --- a/src/Lucene.Net/Document/DateTools.cs +++ b/src/Lucene.Net/Document/DateTools.cs @@ -1,3 +1,4 @@ +using J2N.Text; using System; using System.Globalization; @@ -192,7 +193,7 @@ public static DateTime StringToDate(string dateString) } else { - throw new FormatException("Input is not valid date string: " + dateString); + throw new ParseException("Input is not valid date string: " + dateString, 0); } return date; } diff --git a/src/Lucene.Net/Document/Field.cs b/src/Lucene.Net/Document/Field.cs index f6b59f9f4e..b1fd9f3956 100644 --- a/src/Lucene.Net/Document/Field.cs +++ b/src/Lucene.Net/Document/Field.cs @@ -1,5 +1,6 @@ using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Util; using System; @@ -141,8 +142,8 @@ protected internal object FieldsData /// is null. protected internal Field(string name, FieldType type) { - this.m_name = name ?? throw new ArgumentNullException(nameof(name), "name cannot be null"); - this.m_type = type ?? throw new ArgumentNullException(nameof(type), "type cannot be null"); + this.m_name = name ?? throw new ArgumentNullException(nameof(name), "name cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) + this.m_type = type ?? throw new ArgumentNullException(nameof(type), "type cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -152,13 +153,13 @@ protected internal Field(string name, FieldType type) /// field type /// if is true, or /// if is false. - /// if either the or - /// is null, or if the reader is null + /// if the , or + /// is null public Field(string name, TextReader reader, FieldType type) { if (type is null) { - throw new ArgumentNullException(nameof(type), "type cannot be null"); + throw new ArgumentNullException(nameof(type), "type cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } if (type.IsStored) { @@ -169,8 +170,8 @@ public Field(string name, TextReader reader, FieldType type) throw new ArgumentException("non-tokenized fields must use String values"); } - this.m_name = name ?? throw new ArgumentNullException(nameof(name), "name cannot be null"); - this.FieldsData = reader ?? throw new ArgumentNullException(nameof(reader), "reader cannot be null"); + this.m_name = name ?? throw new ArgumentNullException(nameof(name), "name cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) + this.FieldsData = reader ?? throw new ArgumentNullException(nameof(reader), "reader cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) this.m_type = type; } @@ -181,13 +182,13 @@ public Field(string name, TextReader reader, FieldType type) /// field type /// if is true, or /// if is false, or if is false. - /// if either the or - /// is null, or if the is null + /// if the , or + /// is null public Field(string name, TokenStream tokenStream, FieldType type) { if (type is null) { - throw new ArgumentNullException(nameof(type), "type cannot be null"); + throw new ArgumentNullException(nameof(type), "type cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } if (!type.IsIndexed || !type.IsTokenized) { @@ -198,9 +199,9 @@ public Field(string name, TokenStream tokenStream, FieldType type) throw new ArgumentException("TokenStream fields cannot be stored"); } - this.m_name = name ?? throw new ArgumentNullException(nameof(name), "name cannot be null"); + this.m_name = name ?? throw new ArgumentNullException(nameof(name), "name cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) this.FieldsData = null; - this.m_tokenStream = tokenStream ?? throw new ArgumentNullException(nameof(tokenStream), "tokenStream cannot be null"); + this.m_tokenStream = tokenStream ?? throw new ArgumentNullException(nameof(tokenStream), "tokenStream cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) this.m_type = type; } @@ -254,7 +255,7 @@ public Field(string name, byte[] value, int offset, int length, FieldType type) /// or the is null public Field(string name, BytesRef bytes, FieldType type) { - // LUCENENET specific - rearranged order to take advantage of throw expressions + // LUCENENET specific - rearranged order to take advantage of throw expressions and changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) this.m_name = name ?? throw new ArgumentNullException(nameof(name), "name cannot be null"); this.m_type = type ?? throw new ArgumentNullException(nameof(type), "type cannot be null"); if (type.IsIndexed) @@ -278,7 +279,7 @@ public Field(string name, string value, FieldType type) { if (type is null) { - throw new ArgumentNullException(nameof(type), "type cannot be null"); + throw new ArgumentNullException(nameof(type), "type cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } if (!type.IsStored && !type.IsIndexed) { @@ -290,8 +291,8 @@ public Field(string name, string value, FieldType type) } this.m_type = type; - this.m_name = name ?? throw new ArgumentNullException(nameof(name), "name cannot be null"); - this.FieldsData = value ?? throw new ArgumentNullException(nameof(value), "value cannot be null"); + this.m_name = name ?? throw new ArgumentNullException(nameof(name), "name cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) + this.FieldsData = value ?? throw new ArgumentNullException(nameof(value), "value cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -918,7 +919,7 @@ public virtual TokenStream GetTokenStream(Analyzer analyzer) break; default: - throw new Exception("Should never get here"); + throw AssertionError.Create("Should never get here"); } return internalTokenStream; } @@ -930,7 +931,7 @@ public virtual TokenStream GetTokenStream(Analyzer analyzer) if (!IndexableFieldType.IsTokenized) { - if (stringValue == null) + if (stringValue is null) { throw new ArgumentException("Non-Tokenized Fields must have a String value"); } diff --git a/src/Lucene.Net/Document/FieldType.cs b/src/Lucene.Net/Document/FieldType.cs index 42dcc5e60d..20e1bb1a59 100644 --- a/src/Lucene.Net/Document/FieldType.cs +++ b/src/Lucene.Net/Document/FieldType.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Index; +using Lucene.Net.Index; using Lucene.Net.Util; using System; using System.Text; @@ -73,7 +73,7 @@ private void CheckIfFrozen() { if (frozen) { - throw new InvalidOperationException("this FieldType is already frozen and cannot be changed"); + throw IllegalStateException.Create("this FieldType is already frozen and cannot be changed"); } } @@ -267,7 +267,7 @@ public virtual int NumericPrecisionStep CheckIfFrozen(); if (value < 1) { - throw new ArgumentException("precisionStep must be >= 1 (got " + value + ")"); + throw new ArgumentOutOfRangeException(nameof(NumericPrecisionStep), "precisionStep must be >= 1 (got " + value + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.numericPrecisionStep = value; } diff --git a/src/Lucene.Net/Index/AtomicReaderContext.cs b/src/Lucene.Net/Index/AtomicReaderContext.cs index ffa83bfed0..a3cffb1dec 100644 --- a/src/Lucene.Net/Index/AtomicReaderContext.cs +++ b/src/Lucene.Net/Index/AtomicReaderContext.cs @@ -61,7 +61,7 @@ public override IList Leaves { if (!IsTopLevel) { - throw new NotSupportedException("this is not a top-level context."); + throw UnsupportedOperationException.Create("this is not a top-level context."); } if (Debugging.AssertsEnabled) Debugging.Assert(leaves != null); return leaves; diff --git a/src/Lucene.Net/Index/BaseCompositeReader.cs b/src/Lucene.Net/Index/BaseCompositeReader.cs index d95e1ee192..b6e5a0e6bd 100644 --- a/src/Lucene.Net/Index/BaseCompositeReader.cs +++ b/src/Lucene.Net/Index/BaseCompositeReader.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using System; using System.Collections.Generic; using JCG = J2N.Collections.Generic; @@ -201,7 +201,7 @@ protected internal int ReaderIndex(int docID) { if (docID < 0 || docID >= maxDoc) { - throw new ArgumentException("docID must be >= 0 and < maxDoc=" + maxDoc + " (got docID=" + docID + ")"); + throw new ArgumentOutOfRangeException(nameof(docID), "docID must be >= 0 and < maxDoc=" + maxDoc + " (got docID=" + docID + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } return ReaderUtil.SubIndex(docID, this.starts); } @@ -212,7 +212,7 @@ protected internal int ReaderBase(int readerIndex) { if (readerIndex < 0 || readerIndex >= subReaders.Length) { - throw new ArgumentException("readerIndex must be >= 0 and < getSequentialSubReaders().size()"); + throw new ArgumentOutOfRangeException(nameof(readerIndex), "readerIndex must be >= 0 and < GetSequentialSubReaders().Count"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } return this.starts[readerIndex]; } diff --git a/src/Lucene.Net/Index/BinaryDocValuesFieldUpdates.cs b/src/Lucene.Net/Index/BinaryDocValuesFieldUpdates.cs index 0d9f036097..926db4a03f 100644 --- a/src/Lucene.Net/Index/BinaryDocValuesFieldUpdates.cs +++ b/src/Lucene.Net/Index/BinaryDocValuesFieldUpdates.cs @@ -140,7 +140,7 @@ public override void Add(int doc, object value) // TODO: if the Sorter interface changes to take long indexes, we can remove that limitation if (size == int.MaxValue) { - throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries"); + throw IllegalStateException.Create("cannot support more than System.Int32.MaxValue doc/value entries"); } BytesRef val = (BytesRef)value; @@ -246,7 +246,7 @@ public override void Merge(DocValuesFieldUpdates other) int newSize = size + otherUpdates.size; if (newSize > int.MaxValue) { - throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries; size=" + size + " other.size=" + otherUpdates.size); + throw IllegalStateException.Create("cannot support more than System.Int32.MaxValue doc/value entries; size=" + size + " other.size=" + otherUpdates.size); } docs = docs.Grow(newSize); offsets = offsets.Grow(newSize); diff --git a/src/Lucene.Net/Index/BinaryDocValuesWriter.cs b/src/Lucene.Net/Index/BinaryDocValuesWriter.cs index f519501f4f..733c09d19f 100644 --- a/src/Lucene.Net/Index/BinaryDocValuesWriter.cs +++ b/src/Lucene.Net/Index/BinaryDocValuesWriter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; @@ -73,11 +73,11 @@ public virtual void AddValue(int docID, BytesRef value) { if (docID < addedValues) { - throw new ArgumentException("DocValuesField \"" + fieldInfo.Name + "\" appears more than once in this document (only one value is allowed per field)"); + throw new ArgumentOutOfRangeException(nameof(docID), "DocValuesField \"" + fieldInfo.Name + "\" appears more than once in this document (only one value is allowed per field)"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } - if (value == null) + if (value is null) { - throw new ArgumentException("field=\"" + fieldInfo.Name + "\": null value not allowed"); + throw new ArgumentNullException("field=\"" + fieldInfo.Name + "\": null value not allowed"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } if (value.Length > MAX_LENGTH) { @@ -96,10 +96,10 @@ public virtual void AddValue(int docID, BytesRef value) { bytesOut.WriteBytes(value.Bytes, value.Offset, value.Length); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { // Should never happen! - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } docsWithField = FixedBitSet.EnsureCapacity(docsWithField, docID); docsWithField.Set(docID); @@ -158,10 +158,10 @@ private IEnumerable GetBytesIterator(int maxDocParam) { bytesIterator.ReadBytes(value.Bytes, value.Offset, value.Length); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { // Should never happen! - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } if (docsWithField.Get(upto)) diff --git a/src/Lucene.Net/Index/BitsSlice.cs b/src/Lucene.Net/Index/BitsSlice.cs index 9d712ee969..9fce368962 100644 --- a/src/Lucene.Net/Index/BitsSlice.cs +++ b/src/Lucene.Net/Index/BitsSlice.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Diagnostics; @@ -47,7 +47,7 @@ public bool Get(int doc) { if (doc >= length) { - throw new Exception("doc " + doc + " is out of bounds 0 .. " + (length - 1)); + throw RuntimeException.Create("doc " + doc + " is out of bounds 0 .. " + (length - 1)); } if (Debugging.AssertsEnabled) Debugging.Assert(doc < length,"doc={0} length={1}", doc, length); return parent.Get(doc + start); diff --git a/src/Lucene.Net/Index/CheckIndex.cs b/src/Lucene.Net/Index/CheckIndex.cs index 29722fcf06..05d306932c 100644 --- a/src/Lucene.Net/Index/CheckIndex.cs +++ b/src/Lucene.Net/Index/CheckIndex.cs @@ -1,4 +1,4 @@ -using J2N.Text; +using J2N.Text; using Lucene.Net.Diagnostics; using Lucene.Net.Store; using Lucene.Net.Support; @@ -518,7 +518,7 @@ public virtual Status DoCheckIndex(IList onlySegments) { sis.Read(dir); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Msg(infoStream, "ERROR: could not read any segments file in directory"); result.MissingSegments = true; @@ -568,7 +568,7 @@ public virtual Status DoCheckIndex(IList onlySegments) { input = dir.OpenInput(segmentsFileName, IOContext.READ_ONCE); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Msg(infoStream, "ERROR: could not open segments file in directory"); if (infoStream != null) @@ -587,7 +587,7 @@ public virtual Status DoCheckIndex(IList onlySegments) { format = input.ReadInt32(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Msg(infoStream, "ERROR: could not read segment file version in directory"); if (infoStream != null) @@ -698,7 +698,7 @@ public virtual Status DoCheckIndex(IList onlySegments) string version = info.Info.Version; if (info.Info.DocCount <= 0 && version != null && versionComparer.Compare(version, "4.5") >= 0) { - throw new Exception("illegal number of documents: maxDoc=" + info.Info.DocCount); + throw RuntimeException.Create("illegal number of documents: maxDoc=" + info.Info.DocCount); } int toLoseDocCount = info.Info.DocCount; @@ -766,20 +766,20 @@ public virtual Status DoCheckIndex(IList onlySegments) { if (reader.NumDocs != info.Info.DocCount - info.DelCount) { - throw new Exception("delete count mismatch: info=" + (info.Info.DocCount - info.DelCount) + " vs reader=" + reader.NumDocs); + throw RuntimeException.Create("delete count mismatch: info=" + (info.Info.DocCount - info.DelCount) + " vs reader=" + reader.NumDocs); } if ((info.Info.DocCount - reader.NumDocs) > reader.MaxDoc) { - throw new Exception("too many deleted docs: maxDoc()=" + reader.MaxDoc + " vs del count=" + (info.Info.DocCount - reader.NumDocs)); + throw RuntimeException.Create("too many deleted docs: maxDoc()=" + reader.MaxDoc + " vs del count=" + (info.Info.DocCount - reader.NumDocs)); } if (info.Info.DocCount - numDocs != info.DelCount) { - throw new Exception("delete count mismatch: info=" + info.DelCount + " vs reader=" + (info.Info.DocCount - numDocs)); + throw RuntimeException.Create("delete count mismatch: info=" + info.DelCount + " vs reader=" + (info.Info.DocCount - numDocs)); } IBits liveDocs = reader.LiveDocs; if (liveDocs == null) { - throw new Exception("segment should have deletions, but liveDocs is null"); + throw RuntimeException.Create("segment should have deletions, but liveDocs is null"); } else { @@ -793,7 +793,7 @@ public virtual Status DoCheckIndex(IList onlySegments) } if (numLive != numDocs) { - throw new Exception("liveDocs count mismatch: info=" + numDocs + ", vs bits=" + numLive); + throw RuntimeException.Create("liveDocs count mismatch: info=" + numDocs + ", vs bits=" + numLive); } } @@ -804,7 +804,7 @@ public virtual Status DoCheckIndex(IList onlySegments) { if (info.DelCount != 0) { - throw new Exception("delete count mismatch: info=" + info.DelCount + " vs reader=" + (info.Info.DocCount - numDocs)); + throw RuntimeException.Create("delete count mismatch: info=" + info.DelCount + " vs reader=" + (info.Info.DocCount - numDocs)); } IBits liveDocs = reader.LiveDocs; if (liveDocs != null) @@ -814,7 +814,7 @@ public virtual Status DoCheckIndex(IList onlySegments) { if (!liveDocs.Get(j)) { - throw new Exception("liveDocs mismatch: info says no deletions but doc " + j + " is deleted."); + throw RuntimeException.Create("liveDocs mismatch: info says no deletions but doc " + j + " is deleted."); } } } @@ -822,7 +822,7 @@ public virtual Status DoCheckIndex(IList onlySegments) } if (reader.MaxDoc != info.Info.DocCount) { - throw new Exception("SegmentReader.maxDoc() " + reader.MaxDoc + " != SegmentInfos.docCount " + info.Info.DocCount); + throw RuntimeException.Create("SegmentReader.MaxDoc " + reader.MaxDoc + " != SegmentInfos.docCount " + info.Info.DocCount); } // Test getFieldInfos() @@ -852,28 +852,28 @@ public virtual Status DoCheckIndex(IList onlySegments) // this will cause stats for failed segments to be incremented properly if (segInfoStat.FieldNormStatus.Error != null) { - throw new Exception("Field Norm test failed"); + throw RuntimeException.Create("Field Norm test failed"); } else if (segInfoStat.TermIndexStatus.Error != null) { - throw new Exception("Term Index test failed"); + throw RuntimeException.Create("Term Index test failed"); } else if (segInfoStat.StoredFieldStatus.Error != null) { - throw new Exception("Stored Field test failed"); + throw RuntimeException.Create("Stored Field test failed"); } else if (segInfoStat.TermVectorStatus.Error != null) { - throw new Exception("Term Vector test failed"); + throw RuntimeException.Create("Term Vector test failed"); } else if (segInfoStat.DocValuesStatus.Error != null) { - throw new Exception("DocValues test failed"); + throw RuntimeException.Create("DocValues test failed"); } Msg(infoStream, ""); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { Msg(infoStream, "FAILED"); string comment; @@ -885,7 +885,6 @@ public virtual Status DoCheckIndex(IList onlySegments) // the message. We can't get the error type with StackTrace, we // need ToString() for that. infoStream.WriteLine(t.ToString()); - //infoStream.WriteLine(t.StackTrace); } Msg(infoStream, ""); result.TotLoseDocCount += toLoseDocCount; @@ -961,14 +960,14 @@ public static Status.FieldNormStatus TestFieldNorms(AtomicReader reader, TextWri #pragma warning restore 612, 618 if (reader.GetNormValues(info.Name) != null) { - throw new Exception("field: " + info.Name + " should omit norms but has them!"); + throw RuntimeException.Create("field: " + info.Name + " should omit norms but has them!"); } } } Msg(infoStream, "OK [" + status.TotFields + " fields]"); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Msg(infoStream, "ERROR [" + e.Message + "]"); status.Error = e; @@ -1012,7 +1011,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, // MultiFieldsEnum relies upon this order... if (lastField != null && field.CompareToOrdinal(lastField) <= 0) { - throw new Exception("fields out of order: lastField=" + lastField + " field=" + field); + throw RuntimeException.Create("fields out of order: lastField=" + lastField + " field=" + field); } lastField = field; @@ -1021,11 +1020,11 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, FieldInfo fieldInfo = fieldInfos.FieldInfo(field); if (fieldInfo == null) { - throw new Exception("fieldsEnum inconsistent with fieldInfos, no fieldInfos for: " + field); + throw RuntimeException.Create("fieldsEnum inconsistent with fieldInfos, no fieldInfos for: " + field); } if (!fieldInfo.IsIndexed) { - throw new Exception("fieldsEnum inconsistent with fieldInfos, isIndexed == false for: " + field); + throw RuntimeException.Create("fieldsEnum inconsistent with fieldInfos, isIndexed == false for: " + field); } // TODO: really the codec should not return a field @@ -1051,14 +1050,14 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, if (hasFreqs != expectedHasFreqs) { - throw new Exception("field \"" + field + "\" should have hasFreqs=" + expectedHasFreqs + " but got " + hasFreqs); + throw RuntimeException.Create("field \"" + field + "\" should have hasFreqs=" + expectedHasFreqs + " but got " + hasFreqs); } if (hasFreqs == false) { if (terms.SumTotalTermFreq != -1) { - throw new Exception("field \"" + field + "\" hasFreqs is false, but Terms.getSumTotalTermFreq()=" + terms.SumTotalTermFreq + " (should be -1)"); + throw RuntimeException.Create("field \"" + field + "\" hasFreqs is false, but Terms.getSumTotalTermFreq()=" + terms.SumTotalTermFreq + " (should be -1)"); } } @@ -1068,20 +1067,20 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, bool expectedHasPositions = IndexOptionsComparer.Default.Compare(fieldInfo.IndexOptions, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; if (hasPositions != expectedHasPositions) { - throw new Exception("field \"" + field + "\" should have hasPositions=" + expectedHasPositions + " but got " + hasPositions); + throw RuntimeException.Create("field \"" + field + "\" should have hasPositions=" + expectedHasPositions + " but got " + hasPositions); } bool expectedHasPayloads = fieldInfo.HasPayloads; if (hasPayloads != expectedHasPayloads) { - throw new Exception("field \"" + field + "\" should have hasPayloads=" + expectedHasPayloads + " but got " + hasPayloads); + throw RuntimeException.Create("field \"" + field + "\" should have hasPayloads=" + expectedHasPayloads + " but got " + hasPayloads); } // LUCENENET specific - to avoid boxing, changed from CompareTo() to IndexOptionsComparer.Compare() bool expectedHasOffsets = IndexOptionsComparer.Default.Compare(fieldInfo.IndexOptions, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; if (hasOffsets != expectedHasOffsets) { - throw new Exception("field \"" + field + "\" should have hasOffsets=" + expectedHasOffsets + " but got " + hasOffsets); + throw RuntimeException.Create("field \"" + field + "\" should have hasOffsets=" + expectedHasOffsets + " but got " + hasOffsets); } } @@ -1113,7 +1112,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (termComp.Compare(lastTerm, term) >= 0) { - throw new Exception("terms out of order: lastTerm=" + lastTerm + " term=" + term); + throw RuntimeException.Create("terms out of order: lastTerm=" + lastTerm + " term=" + term); } lastTerm.CopyBytes(term); } @@ -1121,7 +1120,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, int docFreq = termsEnum.DocFreq; if (docFreq <= 0) { - throw new Exception("docfreq: " + docFreq + " is out of bounds"); + throw RuntimeException.Create("docfreq: " + docFreq + " is out of bounds"); } sumDocFreq += docFreq; @@ -1132,7 +1131,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (termsEnum.TotalTermFreq != -1) { - throw new Exception("field \"" + field + "\" hasFreqs is false, but TermsEnum.totalTermFreq()=" + termsEnum.TotalTermFreq + " (should be -1)"); + throw RuntimeException.Create("field \"" + field + "\" hasFreqs is false, but TermsEnum.totalTermFreq()=" + termsEnum.TotalTermFreq + " (should be -1)"); } } @@ -1143,9 +1142,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { ord = termsEnum.Ord; } -#pragma warning disable 168 - catch (NotSupportedException uoe) -#pragma warning restore 168 + catch (Exception uoe) when (uoe.IsUnsupportedOperationException()) { hasOrd = false; } @@ -1155,7 +1152,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, long ordExpected = status.DelTermCount + status.TermCount - termCountStart; if (ord != ordExpected) { - throw new Exception("ord mismatch: TermsEnum has ord=" + ord + " vs actual=" + ordExpected); + throw RuntimeException.Create("ord mismatch: TermsEnum has ord=" + ord + " vs actual=" + ordExpected); } } } @@ -1188,7 +1185,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, freq = docs2.Freq; if (freq <= 0) { - throw new Exception("term " + term + ": doc " + doc + ": freq " + freq + " is out of bounds"); + throw RuntimeException.Create("term " + term + ": doc " + doc + ": freq " + freq + " is out of bounds"); } status.TotPos += freq; totalTermFreq += freq; @@ -1200,18 +1197,18 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, // 1: if (docs2.Freq != 1) { - throw new Exception("term " + term + ": doc " + doc + ": freq " + freq + " != 1 when Terms.hasFreqs() is false"); + throw RuntimeException.Create("term " + term + ": doc " + doc + ": freq " + freq + " != 1 when Terms.hasFreqs() is false"); } } docCount++; if (doc <= lastDoc) { - throw new Exception("term " + term + ": doc " + doc + " <= lastDoc " + lastDoc); + throw RuntimeException.Create("term " + term + ": doc " + doc + " <= lastDoc " + lastDoc); } if (doc >= maxDoc) { - throw new Exception("term " + term + ": doc " + doc + " >= maxDoc " + maxDoc); + throw RuntimeException.Create("term " + term + ": doc " + doc + " >= maxDoc " + maxDoc); } lastDoc = doc; @@ -1226,11 +1223,11 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, if (pos < 0) { - throw new Exception("term " + term + ": doc " + doc + ": pos " + pos + " is out of bounds"); + throw RuntimeException.Create("term " + term + ": doc " + doc + ": pos " + pos + " is out of bounds"); } if (pos < lastPos) { - throw new Exception("term " + term + ": doc " + doc + ": pos " + pos + " < lastPos " + lastPos); + throw RuntimeException.Create("term " + term + ": doc " + doc + ": pos " + pos + " < lastPos " + lastPos); } lastPos = pos; BytesRef payload = postings.GetPayload(); @@ -1240,7 +1237,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, if (Debugging.AssertsEnabled) Debugging.Assert(payload.IsValid()); if (payload.Length < 1) { - throw new Exception("term " + term + ": doc " + doc + ": pos " + pos + " payload length is out of bounds " + payload.Length); + throw RuntimeException.Create("term " + term + ": doc " + doc + ": pos " + pos + " payload length is out of bounds " + payload.Length); } } if (hasOffsets) @@ -1253,19 +1250,19 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (startOffset < 0) { - throw new Exception("term " + term + ": doc " + doc + ": pos " + pos + ": startOffset " + startOffset + " is out of bounds"); + throw RuntimeException.Create("term " + term + ": doc " + doc + ": pos " + pos + ": startOffset " + startOffset + " is out of bounds"); } if (startOffset < lastOffset) { - throw new Exception("term " + term + ": doc " + doc + ": pos " + pos + ": startOffset " + startOffset + " < lastStartOffset " + lastOffset); + throw RuntimeException.Create("term " + term + ": doc " + doc + ": pos " + pos + ": startOffset " + startOffset + " < lastStartOffset " + lastOffset); } if (endOffset < 0) { - throw new Exception("term " + term + ": doc " + doc + ": pos " + pos + ": endOffset " + endOffset + " is out of bounds"); + throw RuntimeException.Create("term " + term + ": doc " + doc + ": pos " + pos + ": endOffset " + endOffset + " is out of bounds"); } if (endOffset < startOffset) { - throw new Exception("term " + term + ": doc " + doc + ": pos " + pos + ": endOffset " + endOffset + " < startOffset " + startOffset); + throw RuntimeException.Create("term " + term + ": doc " + doc + ": pos " + pos + ": endOffset " + endOffset + " < startOffset " + startOffset); } } lastOffset = startOffset; @@ -1316,18 +1313,18 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, if (docCount != docFreq) { - throw new Exception("term " + term + " docFreq=" + docFreq + " != tot docs w/o deletions " + docCount); + throw RuntimeException.Create("term " + term + " docFreq=" + docFreq + " != tot docs w/o deletions " + docCount); } if (hasTotalTermFreq) { if (totalTermFreq2 <= 0) { - throw new Exception("totalTermFreq: " + totalTermFreq2 + " is out of bounds"); + throw RuntimeException.Create("totalTermFreq: " + totalTermFreq2 + " is out of bounds"); } sumTotalTermFreq += totalTermFreq; if (totalTermFreq != totalTermFreq2) { - throw new Exception("term " + term + " totalTermFreq=" + totalTermFreq2 + " != recomputed totalTermFreq=" + totalTermFreq); + throw RuntimeException.Create("term " + term + " totalTermFreq=" + totalTermFreq2 + " != recomputed totalTermFreq=" + totalTermFreq); } } @@ -1347,12 +1344,12 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (docID < skipDocID) { - throw new Exception("term " + term + ": advance(docID=" + skipDocID + ") returned docID=" + docID); + throw RuntimeException.Create("term " + term + ": advance(docID=" + skipDocID + ") returned docID=" + docID); } int freq = postings.Freq; if (freq <= 0) { - throw new Exception("termFreq " + freq + " is out of bounds"); + throw RuntimeException.Create("termFreq " + freq + " is out of bounds"); } int lastPosition = -1; int lastOffset = 0; @@ -1362,11 +1359,11 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, if (pos < 0) { - throw new Exception("position " + pos + " is out of bounds"); + throw RuntimeException.Create("position " + pos + " is out of bounds"); } if (pos < lastPosition) { - throw new Exception("position " + pos + " is < lastPosition " + lastPosition); + throw RuntimeException.Create("position " + pos + " is < lastPosition " + lastPosition); } lastPosition = pos; if (hasOffsets) @@ -1379,19 +1376,19 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (startOffset < 0) { - throw new Exception("term " + term + ": doc " + docID + ": pos " + pos + ": startOffset " + startOffset + " is out of bounds"); + throw RuntimeException.Create("term " + term + ": doc " + docID + ": pos " + pos + ": startOffset " + startOffset + " is out of bounds"); } if (startOffset < lastOffset) { - throw new Exception("term " + term + ": doc " + docID + ": pos " + pos + ": startOffset " + startOffset + " < lastStartOffset " + lastOffset); + throw RuntimeException.Create("term " + term + ": doc " + docID + ": pos " + pos + ": startOffset " + startOffset + " < lastStartOffset " + lastOffset); } if (endOffset < 0) { - throw new Exception("term " + term + ": doc " + docID + ": pos " + pos + ": endOffset " + endOffset + " is out of bounds"); + throw RuntimeException.Create("term " + term + ": doc " + docID + ": pos " + pos + ": endOffset " + endOffset + " is out of bounds"); } if (endOffset < startOffset) { - throw new Exception("term " + term + ": doc " + docID + ": pos " + pos + ": endOffset " + endOffset + " < startOffset " + startOffset); + throw RuntimeException.Create("term " + term + ": doc " + docID + ": pos " + pos + ": endOffset " + endOffset + " < startOffset " + startOffset); } } lastOffset = startOffset; @@ -1405,7 +1402,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, } if (nextDocID <= docID) { - throw new Exception("term " + term + ": Advance(docID=" + skipDocID + "), then .Next() returned docID=" + nextDocID + " vs prev docID=" + docID); + throw RuntimeException.Create("term " + term + ": Advance(docID=" + skipDocID + "), then .Next() returned docID=" + nextDocID + " vs prev docID=" + docID); } } } @@ -1425,7 +1422,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (docID < skipDocID) { - throw new Exception("term " + term + ": Advance(docID=" + skipDocID + ") returned docID=" + docID); + throw RuntimeException.Create("term " + term + ": Advance(docID=" + skipDocID + ") returned docID=" + docID); } int nextDocID = docs.NextDoc(); if (nextDocID == DocIdSetIterator.NO_MORE_DOCS) @@ -1434,7 +1431,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, } if (nextDocID <= docID) { - throw new Exception("term " + term + ": Advance(docID=" + skipDocID + "), then .Next() returned docID=" + nextDocID + " vs prev docID=" + docID); + throw RuntimeException.Create("term " + term + ": Advance(docID=" + skipDocID + "), then .Next() returned docID=" + nextDocID + " vs prev docID=" + docID); } } } @@ -1468,7 +1465,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, long v = fields.GetTerms(field).SumTotalTermFreq; if (v != -1 && sumTotalTermFreq != v) { - throw new Exception("sumTotalTermFreq for field " + field + "=" + v + " != recomputed sumTotalTermFreq=" + sumTotalTermFreq); + throw RuntimeException.Create("sumTotalTermFreq for field " + field + "=" + v + " != recomputed sumTotalTermFreq=" + sumTotalTermFreq); } } @@ -1477,7 +1474,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, long v = fields.GetTerms(field).SumDocFreq; if (v != -1 && sumDocFreq != v) { - throw new Exception("sumDocFreq for field " + field + "=" + v + " != recomputed sumDocFreq=" + sumDocFreq); + throw RuntimeException.Create("sumDocFreq for field " + field + "=" + v + " != recomputed sumDocFreq=" + sumDocFreq); } } @@ -1486,7 +1483,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, int v = fieldTerms.DocCount; if (v != -1 && visitedDocs.Cardinality() != v) { - throw new Exception("docCount for field " + field + "=" + v + " != recomputed docCount=" + visitedDocs.Cardinality()); + throw RuntimeException.Create("docCount for field " + field + "=" + v + " != recomputed docCount=" + visitedDocs.Cardinality()); } } @@ -1495,7 +1492,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (termsEnum.SeekCeil(lastTerm) != TermsEnum.SeekStatus.FOUND) { - throw new Exception("seek to last term " + lastTerm + " failed"); + throw RuntimeException.Create("seek to last term " + lastTerm + " failed"); } int expectedDocFreq = termsEnum.DocFreq; @@ -1507,7 +1504,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, } if (docFreq != expectedDocFreq) { - throw new Exception("docFreq for last term " + lastTerm + "=" + expectedDocFreq + " != recomputed docFreq=" + docFreq); + throw RuntimeException.Create("docFreq for last term " + lastTerm + "=" + expectedDocFreq + " != recomputed docFreq=" + docFreq); } } @@ -1520,7 +1517,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, if (termCount != -1 && termCount != status.DelTermCount + status.TermCount - termCountStart) { - throw new Exception("termCount mismatch " + (status.DelTermCount + termCount) + " vs " + (status.TermCount - termCountStart)); + throw RuntimeException.Create("termCount mismatch " + (status.DelTermCount + termCount) + " vs " + (status.TermCount - termCountStart)); } } @@ -1546,13 +1543,13 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (termsEnum.SeekCeil(seekTerms[i]) != TermsEnum.SeekStatus.FOUND) { - throw new Exception("seek to existing term " + seekTerms[i] + " failed"); + throw RuntimeException.Create("seek to existing term " + seekTerms[i] + " failed"); } docs = termsEnum.Docs(liveDocs, docs, DocsFlags.NONE); if (docs == null) { - throw new Exception("null DocsEnum from to existing term " + seekTerms[i]); + throw RuntimeException.Create("null DocsEnum from to existing term " + seekTerms[i]); } while (docs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) @@ -1567,14 +1564,14 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (!termsEnum.SeekExact(seekTerms[i])) { - throw new Exception("seek to existing term " + seekTerms[i] + " failed"); + throw RuntimeException.Create("seek to existing term " + seekTerms[i] + " failed"); } totDocFreq += termsEnum.DocFreq; docs = termsEnum.Docs(null, docs, DocsFlags.NONE); if (docs == null) { - throw new Exception("null DocsEnum from to existing term " + seekTerms[i]); + throw RuntimeException.Create("null DocsEnum from to existing term " + seekTerms[i]); } while (docs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) @@ -1585,12 +1582,12 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, if (totDocCount > totDocCountNoDeletes) { - throw new Exception("more postings with deletes=" + totDocCount + " than without=" + totDocCountNoDeletes); + throw RuntimeException.Create("more postings with deletes=" + totDocCount + " than without=" + totDocCountNoDeletes); } if (totDocCountNoDeletes != totDocFreq) { - throw new Exception("docfreqs=" + totDocFreq + " != recomputed docfreqs=" + totDocCountNoDeletes); + throw RuntimeException.Create("docfreqs=" + totDocFreq + " != recomputed docfreqs=" + totDocCountNoDeletes); } } } @@ -1603,11 +1600,11 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, { if (fieldCount < 0) { - throw new Exception("invalid fieldCount: " + fieldCount); + throw RuntimeException.Create("invalid fieldCount: " + fieldCount); } if (fieldCount != computedFieldCount) { - throw new Exception("fieldCount mismatch " + fieldCount + " vs recomputed field count " + computedFieldCount); + throw RuntimeException.Create("fieldCount mismatch " + fieldCount + " vs recomputed field count " + computedFieldCount); } } @@ -1620,7 +1617,7 @@ private static Status.TermIndexStatus CheckFields(Fields fields, IBits liveDocs, if (uniqueTermCountAllFields != -1 && status.TermCount + status.DelTermCount != uniqueTermCountAllFields) { - throw new Exception("termCount mismatch " + uniqueTermCountAllFields + " vs " + (status.TermCount + status.DelTermCount)); + throw RuntimeException.Create("termCount mismatch " + uniqueTermCountAllFields + " vs " + (status.TermCount + status.DelTermCount)); } if (doPrint) @@ -1683,7 +1680,7 @@ public static Status.TermIndexStatus TestPostings(AtomicReader reader, TextWrite CheckFields(fields, null, maxDoc, fieldInfos, true, false, infoStream, verbose); } } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Msg(infoStream, "ERROR: " + e); status = new Status.TermIndexStatus(); @@ -1734,12 +1731,12 @@ public static Status.StoredFieldStatus TestStoredFields(AtomicReader reader, Tex // Validate docCount if (status.DocCount != reader.NumDocs) { - throw new Exception("docCount=" + status.DocCount + " but saw " + status.DocCount + " undeleted docs"); + throw RuntimeException.Create("docCount=" + status.DocCount + " but saw " + status.DocCount + " undeleted docs"); } Msg(infoStream, "OK [" + status.TotFields + " total field count; avg " + ((((float)status.TotFields) / status.DocCount)).ToString(CultureInfo.InvariantCulture.NumberFormat) + " fields per doc]"); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Msg(infoStream, "ERROR [" + e.Message + "]"); status.Error = e; @@ -1781,14 +1778,14 @@ public static Status.DocValuesStatus TestDocValues(AtomicReader reader, TextWrit { if (reader.GetBinaryDocValues(fieldInfo.Name) != null || reader.GetNumericDocValues(fieldInfo.Name) != null || reader.GetSortedDocValues(fieldInfo.Name) != null || reader.GetSortedSetDocValues(fieldInfo.Name) != null || reader.GetDocsWithField(fieldInfo.Name) != null) { - throw new Exception("field: " + fieldInfo.Name + " has docvalues but should omit them!"); + throw RuntimeException.Create("field: " + fieldInfo.Name + " has docvalues but should omit them!"); } } } Msg(infoStream, "OK [" + status.TotalValueFields + " docvalues fields; " + status.TotalBinaryFields + " BINARY; " + status.TotalNumericFields + " NUMERIC; " + status.TotalSortedFields + " SORTED; " + status.TotalSortedSetFields + " SORTED_SET]"); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Msg(infoStream, "ERROR [" + e.Message + "]"); status.Error = e; @@ -1813,7 +1810,7 @@ private static void CheckBinaryDocValues(string fieldName, AtomicReader reader, if (Debugging.AssertsEnabled) Debugging.Assert(scratch.IsValid()); if (docsWithField.Get(i) == false && scratch.Length > 0) { - throw new Exception("dv for field: " + fieldName + " is missing but has value=" + scratch + " for doc: " + i); + throw RuntimeException.Create("dv for field: " + fieldName + " is missing but has value=" + scratch + " for doc: " + i); } } } @@ -1831,18 +1828,18 @@ private static void CheckSortedDocValues(string fieldName, AtomicReader reader, { if (docsWithField.Get(i)) { - throw new Exception("dv for field: " + fieldName + " has -1 ord but is not marked missing for doc: " + i); + throw RuntimeException.Create("dv for field: " + fieldName + " has -1 ord but is not marked missing for doc: " + i); } } else if (ord < -1 || ord > maxOrd) { - throw new Exception("ord out of bounds: " + ord); + throw RuntimeException.Create("ord out of bounds: " + ord); } else { if (!docsWithField.Get(i)) { - throw new Exception("dv for field: " + fieldName + " is missing but has ord=" + ord + " for doc: " + i); + throw RuntimeException.Create("dv for field: " + fieldName + " is missing but has ord=" + ord + " for doc: " + i); } maxOrd2 = Math.Max(maxOrd2, ord); seenOrds.Set(ord); @@ -1850,11 +1847,11 @@ private static void CheckSortedDocValues(string fieldName, AtomicReader reader, } if (maxOrd != maxOrd2) { - throw new Exception("dv for field: " + fieldName + " reports wrong maxOrd=" + maxOrd + " but this is not the case: " + maxOrd2); + throw RuntimeException.Create("dv for field: " + fieldName + " reports wrong maxOrd=" + maxOrd + " but this is not the case: " + maxOrd2); } if (seenOrds.Cardinality() != dv.ValueCount) { - throw new Exception("dv for field: " + fieldName + " has holes in its ords, ValueCount=" + dv.ValueCount + " but only used: " + seenOrds.Cardinality()); + throw RuntimeException.Create("dv for field: " + fieldName + " has holes in its ords, ValueCount=" + dv.ValueCount + " but only used: " + seenOrds.Cardinality()); } BytesRef lastValue = null; BytesRef scratch = new BytesRef(); @@ -1866,7 +1863,7 @@ private static void CheckSortedDocValues(string fieldName, AtomicReader reader, { if (scratch.CompareTo(lastValue) <= 0) { - throw new Exception("dv for field: " + fieldName + " has ords out of order: " + lastValue + " >=" + scratch); + throw RuntimeException.Create("dv for field: " + fieldName + " has ords out of order: " + lastValue + " >=" + scratch); } } lastValue = BytesRef.DeepCopyOf(scratch); @@ -1890,18 +1887,18 @@ private static void CheckSortedSetDocValues(string fieldName, AtomicReader reade { if (ord <= lastOrd) { - throw new Exception("ords out of order: " + ord + " <= " + lastOrd + " for doc: " + i); + throw RuntimeException.Create("ords out of order: " + ord + " <= " + lastOrd + " for doc: " + i); } if (ord < 0 || ord > maxOrd) { - throw new Exception("ord out of bounds: " + ord); + throw RuntimeException.Create("ord out of bounds: " + ord); } if (dv is RandomAccessOrds randomAccessOrds2) { long ord2 = randomAccessOrds2.OrdAt(ordCount); if (ord != ord2) { - throw new Exception("ordAt(" + ordCount + ") inconsistent, expected=" + ord + ",got=" + ord2 + " for doc: " + i); + throw RuntimeException.Create("OrdAt(" + ordCount + ") inconsistent, expected=" + ord + ",got=" + ord2 + " for doc: " + i); } } lastOrd = ord; @@ -1911,14 +1908,14 @@ private static void CheckSortedSetDocValues(string fieldName, AtomicReader reade } if (ordCount == 0) { - throw new Exception("dv for field: " + fieldName + " has no ordinals but is not marked missing for doc: " + i); + throw RuntimeException.Create("dv for field: " + fieldName + " has no ordinals but is not marked missing for doc: " + i); } if (dv is RandomAccessOrds randomAccessOrds) { long ordCount2 = randomAccessOrds.Cardinality(); if (ordCount != ordCount2) { - throw new Exception("cardinality inconsistent, expected=" + ordCount + ",got=" + ordCount2 + " for doc: " + i); + throw RuntimeException.Create("cardinality inconsistent, expected=" + ordCount + ",got=" + ordCount2 + " for doc: " + i); } } } @@ -1927,25 +1924,25 @@ private static void CheckSortedSetDocValues(string fieldName, AtomicReader reade long o = dv.NextOrd(); if (o != SortedSetDocValues.NO_MORE_ORDS) { - throw new Exception("dv for field: " + fieldName + " is marked missing but has ord=" + o + " for doc: " + i); + throw RuntimeException.Create("dv for field: " + fieldName + " is marked missing but has ord=" + o + " for doc: " + i); } if (dv is RandomAccessOrds randomAccessOrds) { long ordCount2 = randomAccessOrds.Cardinality(); if (ordCount2 != 0) { - throw new Exception("dv for field: " + fieldName + " is marked missing but has cardinality " + ordCount2 + " for doc: " + i); + throw RuntimeException.Create("dv for field: " + fieldName + " is marked missing but has cardinality " + ordCount2 + " for doc: " + i); } } } } if (maxOrd != maxOrd2) { - throw new Exception("dv for field: " + fieldName + " reports wrong maxOrd=" + maxOrd + " but this is not the case: " + maxOrd2); + throw RuntimeException.Create("dv for field: " + fieldName + " reports wrong maxOrd=" + maxOrd + " but this is not the case: " + maxOrd2); } if (seenOrds.Cardinality() != dv.ValueCount) { - throw new Exception("dv for field: " + fieldName + " has holes in its ords, valueCount=" + dv.ValueCount + " but only used: " + seenOrds.Cardinality()); + throw RuntimeException.Create("dv for field: " + fieldName + " has holes in its ords, valueCount=" + dv.ValueCount + " but only used: " + seenOrds.Cardinality()); } BytesRef lastValue = null; @@ -1958,7 +1955,7 @@ private static void CheckSortedSetDocValues(string fieldName, AtomicReader reade { if (scratch.CompareTo(lastValue) <= 0) { - throw new Exception("dv for field: " + fieldName + " has ords out of order: " + lastValue + " >=" + scratch); + throw RuntimeException.Create("dv for field: " + fieldName + " has ords out of order: " + lastValue + " >=" + scratch); } } lastValue = BytesRef.DeepCopyOf(scratch); @@ -1972,7 +1969,7 @@ private static void CheckNumericDocValues(string fieldName, AtomicReader reader, long value = ndv.Get(i); if (docsWithField.Get(i) == false && value != 0) { - throw new Exception("dv for field: " + fieldName + " is marked missing but has value=" + value + " for doc: " + i); + throw RuntimeException.Create("dv for field: " + fieldName + " is marked missing but has value=" + value + " for doc: " + i); } } } @@ -1982,11 +1979,11 @@ private static void CheckDocValues(FieldInfo fi, AtomicReader reader, /*StreamWr IBits docsWithField = reader.GetDocsWithField(fi.Name); if (docsWithField == null) { - throw new Exception(fi.Name + " docsWithField does not exist"); + throw RuntimeException.Create(fi.Name + " docsWithField does not exist"); } else if (docsWithField.Length != reader.MaxDoc) { - throw new Exception(fi.Name + " docsWithField has incorrect length: " + docsWithField.Length + ",expected: " + reader.MaxDoc); + throw RuntimeException.Create(fi.Name + " docsWithField has incorrect length: " + docsWithField.Length + ",expected: " + reader.MaxDoc); } switch (fi.DocValuesType) { @@ -1995,7 +1992,7 @@ private static void CheckDocValues(FieldInfo fi, AtomicReader reader, /*StreamWr CheckSortedDocValues(fi.Name, reader, reader.GetSortedDocValues(fi.Name), docsWithField); if (reader.GetBinaryDocValues(fi.Name) != null || reader.GetNumericDocValues(fi.Name) != null || reader.GetSortedSetDocValues(fi.Name) != null) { - throw new Exception(fi.Name + " returns multiple docvalues types!"); + throw RuntimeException.Create(fi.Name + " returns multiple docvalues types!"); } break; @@ -2004,7 +2001,7 @@ private static void CheckDocValues(FieldInfo fi, AtomicReader reader, /*StreamWr CheckSortedSetDocValues(fi.Name, reader, reader.GetSortedSetDocValues(fi.Name), docsWithField); if (reader.GetBinaryDocValues(fi.Name) != null || reader.GetNumericDocValues(fi.Name) != null || reader.GetSortedDocValues(fi.Name) != null) { - throw new Exception(fi.Name + " returns multiple docvalues types!"); + throw RuntimeException.Create(fi.Name + " returns multiple docvalues types!"); } break; @@ -2013,7 +2010,7 @@ private static void CheckDocValues(FieldInfo fi, AtomicReader reader, /*StreamWr CheckBinaryDocValues(fi.Name, reader, reader.GetBinaryDocValues(fi.Name), docsWithField); if (reader.GetNumericDocValues(fi.Name) != null || reader.GetSortedDocValues(fi.Name) != null || reader.GetSortedSetDocValues(fi.Name) != null) { - throw new Exception(fi.Name + " returns multiple docvalues types!"); + throw RuntimeException.Create(fi.Name + " returns multiple docvalues types!"); } break; @@ -2022,12 +2019,12 @@ private static void CheckDocValues(FieldInfo fi, AtomicReader reader, /*StreamWr CheckNumericDocValues(fi.Name, reader, reader.GetNumericDocValues(fi.Name), docsWithField); if (reader.GetBinaryDocValues(fi.Name) != null || reader.GetSortedDocValues(fi.Name) != null || reader.GetSortedSetDocValues(fi.Name) != null) { - throw new Exception(fi.Name + " returns multiple docvalues types!"); + throw RuntimeException.Create(fi.Name + " returns multiple docvalues types!"); } break; default: - throw new InvalidOperationException(); + throw AssertionError.Create(); } } @@ -2036,11 +2033,11 @@ private static void CheckNorms(FieldInfo fi, AtomicReader reader /*, TextWriter switch (fi.NormType) { case DocValuesType.NUMERIC: - CheckNumericDocValues(fi.Name, reader, reader.GetNormValues(fi.Name), new Lucene.Net.Util.Bits.MatchAllBits(reader.MaxDoc)); + CheckNumericDocValues(fi.Name, reader, reader.GetNormValues(fi.Name), new Bits.MatchAllBits(reader.MaxDoc)); break; default: - throw new InvalidOperationException("wtf: " + fi.NormType); + throw AssertionError.Create("wtf: " + fi.NormType); } } @@ -2131,7 +2128,7 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW FieldInfo fieldInfo = fieldInfos.FieldInfo(field); if (!fieldInfo.HasVectors) { - throw new Exception("docID=" + j + " has term vectors for field=" + field + " but FieldInfo has storeTermVector=false"); + throw RuntimeException.Create("docID=" + j + " has term vectors for field=" + field + " but FieldInfo has storeTermVector=false"); } if (crossCheckTermVectors) @@ -2146,7 +2143,7 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW Terms postingsTerms = postingsFields.GetTerms(field); if (postingsTerms == null) { - throw new Exception("vector field=" + field + " does not exist in postings; doc=" + j); + throw RuntimeException.Create("vector field=" + field + " does not exist in postings; doc=" + j); } postingsTermsEnum = postingsTerms.GetEnumerator(postingsTermsEnum); @@ -2183,7 +2180,7 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW DocsEnum postingsDocs2; if (!postingsTermsEnum.SeekExact(term)) { - throw new Exception("vector term=" + term + " field=" + field + " does not exist in postings; doc=" + j); + throw RuntimeException.Create("vector term=" + term + " field=" + field + " does not exist in postings; doc=" + j); } postingsPostings = postingsTermsEnum.DocsAndPositions(null, postingsPostings); if (postingsPostings == null) @@ -2192,7 +2189,7 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW postingsDocs = postingsTermsEnum.Docs(null, postingsDocs); if (postingsDocs == null) { - throw new Exception("vector term=" + term + " field=" + field + " does not exist in postings; doc=" + j); + throw RuntimeException.Create("vector term=" + term + " field=" + field + " does not exist in postings; doc=" + j); } } @@ -2208,14 +2205,14 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW int advanceDoc = postingsDocs2.Advance(j); if (advanceDoc != j) { - throw new Exception("vector term=" + term + " field=" + field + ": doc=" + j + " was not found in postings (got: " + advanceDoc + ")"); + throw RuntimeException.Create("vector term=" + term + " field=" + field + ": doc=" + j + " was not found in postings (got: " + advanceDoc + ")"); } int doc = docs2.NextDoc(); if (doc != 0) { - throw new Exception("vector for doc " + j + " didn't return docID=0: got docID=" + doc); + throw RuntimeException.Create("vector for doc " + j + " didn't return docID=0: got docID=" + doc); } if (postingsHasFreq) @@ -2223,7 +2220,7 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW int tf = docs2.Freq; if (postingsHasFreq && postingsDocs2.Freq != tf) { - throw new Exception("vector term=" + term + " field=" + field + " doc=" + j + ": freq=" + tf + " differs from postings freq=" + postingsDocs2.Freq); + throw RuntimeException.Create("vector term=" + term + " field=" + field + " doc=" + j + ": freq=" + tf + " differs from postings freq=" + postingsDocs2.Freq); } if (hasProx) @@ -2236,7 +2233,7 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW int postingsPos = postingsPostings.NextPosition(); if (terms.HasPositions && pos != postingsPos) { - throw new Exception("vector term=" + term + " field=" + field + " doc=" + j + ": pos=" + pos + " differs from postings pos=" + postingsPos); + throw RuntimeException.Create("vector term=" + term + " field=" + field + " doc=" + j + ": pos=" + pos + " differs from postings pos=" + postingsPos); } } @@ -2247,10 +2244,10 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW // TODO: these are too anal...? /* if (endOffset < startOffset) { - throw new RuntimeException("vector startOffset=" + startOffset + " is > endOffset=" + endOffset); + throw RuntimeException.Create("vector startOffset=" + startOffset + " is > endOffset=" + endOffset); } if (startOffset < lastStartOffset) { - throw new RuntimeException("vector startOffset=" + startOffset + " is < prior startOffset=" + lastStartOffset); + throw RuntimeException.Create("vector startOffset=" + startOffset + " is < prior startOffset=" + lastStartOffset); } lastStartOffset = startOffset; */ @@ -2262,11 +2259,11 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW int postingsEndOffset = postingsPostings.EndOffset; if (startOffset != -1 && postingsStartOffset != -1 && startOffset != postingsStartOffset) { - throw new Exception("vector term=" + term + " field=" + field + " doc=" + j + ": startOffset=" + startOffset + " differs from postings startOffset=" + postingsStartOffset); + throw RuntimeException.Create("vector term=" + term + " field=" + field + " doc=" + j + ": startOffset=" + startOffset + " differs from postings startOffset=" + postingsStartOffset); } if (endOffset != -1 && postingsEndOffset != -1 && endOffset != postingsEndOffset) { - throw new Exception("vector term=" + term + " field=" + field + " doc=" + j + ": endOffset=" + endOffset + " differs from postings endOffset=" + postingsEndOffset); + throw RuntimeException.Create("vector term=" + term + " field=" + field + " doc=" + j + ": endOffset=" + endOffset + " differs from postings endOffset=" + postingsEndOffset); } } @@ -2287,7 +2284,7 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW // postings has payloads too, it should not have one at this position if (postingsPostings.GetPayload() != null) { - throw new Exception("vector term=" + term + " field=" + field + " doc=" + j + " has no payload but postings does: " + postingsPostings.GetPayload()); + throw RuntimeException.Create("vector term=" + term + " field=" + field + " doc=" + j + " has no payload but postings does: " + postingsPostings.GetPayload()); } } else @@ -2296,12 +2293,12 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW // postings should also have one at this position, with the same bytes. if (postingsPostings.GetPayload() == null) { - throw new Exception("vector term=" + term + " field=" + field + " doc=" + j + " has payload=" + payload + " but postings does not."); + throw RuntimeException.Create("vector term=" + term + " field=" + field + " doc=" + j + " has payload=" + payload + " but postings does not."); } BytesRef postingsPayload = postingsPostings.GetPayload(); if (!payload.Equals(postingsPayload)) { - throw new Exception("vector term=" + term + " field=" + field + " doc=" + j + " has payload=" + payload + " but differs from postings payload=" + postingsPayload); + throw RuntimeException.Create("vector term=" + term + " field=" + field + " doc=" + j + " has payload=" + payload + " but differs from postings payload=" + postingsPayload); } } } @@ -2316,7 +2313,7 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW float vectorAvg = status.DocCount == 0 ? 0 : status.TotVectors / (float)status.DocCount; Msg(infoStream, "OK [" + status.TotVectors + " total vector count; avg " + vectorAvg.ToString(CultureInfo.InvariantCulture.NumberFormat) + " term/freq vector fields per doc]"); } - catch (Exception e) + catch (Exception e) when (e.IsThrowable()) { Msg(infoStream, "ERROR [" + e.Message + "]"); status.Error = e; @@ -2350,6 +2347,9 @@ public static Status.TermVectorStatus TestTermVectors(AtomicReader reader, TextW /// public virtual void FixIndex(Status result) { + if (result is null) + throw new ArgumentNullException(nameof(result)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) + if (result.Partial) { throw new ArgumentException("can only fix an index that was fully checked (this status checked a subset of segments)"); @@ -2509,7 +2509,7 @@ public static void Main(string[] args) dir = CommandLineUtil.NewFSDirectory(dirImpl, new DirectoryInfo(indexPath)); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { // LUCENENET specific - we only output from our CLI wrapper throw new ArgumentException("ERROR: could not open directory \"" + indexPath + "\"; exiting\n" + t.ToString()); diff --git a/src/Lucene.Net/Index/CoalescedUpdates.cs b/src/Lucene.Net/Index/CoalescedUpdates.cs index 6394052eb3..2d74fe564c 100644 --- a/src/Lucene.Net/Index/CoalescedUpdates.cs +++ b/src/Lucene.Net/Index/CoalescedUpdates.cs @@ -150,7 +150,7 @@ public bool MoveNext() public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public QueryAndLimit Current => current; diff --git a/src/Lucene.Net/Index/CompositeReaderContext.cs b/src/Lucene.Net/Index/CompositeReaderContext.cs index f0f28ab56a..5b4be75f1c 100644 --- a/src/Lucene.Net/Index/CompositeReaderContext.cs +++ b/src/Lucene.Net/Index/CompositeReaderContext.cs @@ -68,7 +68,7 @@ public override IList Leaves { if (!IsTopLevel) { - throw new NotSupportedException("this is not a top-level context."); + throw UnsupportedOperationException.Create("this is not a top-level context."); } if (Debugging.AssertsEnabled) Debugging.Assert(leaves != null); return leaves; diff --git a/src/Lucene.Net/Index/ConcurrentMergeScheduler.cs b/src/Lucene.Net/Index/ConcurrentMergeScheduler.cs index d6ce84933e..10dfdee6af 100644 --- a/src/Lucene.Net/Index/ConcurrentMergeScheduler.cs +++ b/src/Lucene.Net/Index/ConcurrentMergeScheduler.cs @@ -115,11 +115,11 @@ public virtual void SetMaxMergesAndThreads(int maxMergeCount, int maxThreadCount { if (maxThreadCount < 1) { - throw new ArgumentException("maxThreadCount should be at least 1"); + throw new ArgumentOutOfRangeException(nameof(maxThreadCount), "maxThreadCount should be at least 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (maxMergeCount < 1) { - throw new ArgumentException("maxMergeCount should be at least 1"); + throw new ArgumentOutOfRangeException(nameof(maxMergeCount), "maxMergeCount should be at least 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (maxThreadCount > maxMergeCount) { @@ -171,7 +171,7 @@ public virtual void SetMergeThreadPriority(int priority) { if (priority > (int)ThreadPriority.Highest || priority < (int)ThreadPriority.Lowest) { - throw new ArgumentException("priority must be in range " + (int)ThreadPriority.Highest + " .. " + (int)ThreadPriority.Lowest + " inclusive"); + throw new ArgumentOutOfRangeException("priority must be in range " + (int)ThreadPriority.Highest + " .. " + (int)ThreadPriority.Lowest + " inclusive"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } mergeThreadPriority = priority; UpdateMergeThreads(); @@ -342,9 +342,7 @@ public virtual void Sync() { toSync.Join(); } -#pragma warning disable 168 - catch (ThreadInterruptedException ie) -#pragma warning restore 168 + catch (Exception ie) when (ie.IsInterruptedException()) { // ignore this Exception, we will retry until all threads are dead interrupted = true; @@ -436,14 +434,8 @@ public override void Merge(IndexWriter writer, MergeTrigger trigger, bool newMer { Message(" too many merges; stalling..."); } - //try - //{ Monitor.Wait(this); - //} - //catch (ThreadInterruptedException ie) // LUCENENET NOTE: Senseless to catch and rethrow the same exception type - //{ - // throw new ThreadInterruptedException(ie.ToString(), ie); - //} + // LUCENENET: Just let ThreadInterruptedException propagate. Note that it could be thrown above on lock (this). } if (IsVerbose) @@ -595,22 +587,25 @@ public virtual MergePolicy.OneMerge CurrentMerge /// Set the priority of this thread. public virtual void SetThreadPriority(ThreadPriority priority) { - try - { + // LUCENENET: We don't have to worry about JRE bugs here, and + // SecurityException is not thrown from Thread.Priority. The exceptions + // it throws (ArgumentException and ThreadStateException) are both valid + // cases and are extremely unlikely (we never abort, and users would have to cast + // an invalid int to a ThreadPriority). + //try + //{ Priority = priority; - } -#pragma warning disable 168 - catch (NullReferenceException npe) - { - // Strangely, Sun's JDK 1.5 on Linux sometimes - // throws NPE out of here... - } - catch (SecurityException /*se*/) // LUCENENET: IDE0059: Remove unnecessary value assignment -#pragma warning restore 168 - { - // Ignore this because we will still run fine with - // normal thread priority - } + //} + //catch (NullReferenceException npe) + //{ + // // Strangely, Sun's JDK 1.5 on Linux sometimes + // // throws NPE out of here... + //} + //catch (SecurityException se) + //{ + // // Ignore this because we will still run fine with + // // normal thread priority + //} } public override void Run() @@ -662,7 +657,7 @@ public override void Run() outerInstance.Message(" merge thread: done"); } } - catch (Exception exc) + catch (Exception exc) when (exc.IsThrowable()) { // Ignore the exception if it was due to abort: if (!(exc is MergePolicy.MergeAbortedException)) @@ -695,8 +690,6 @@ public override void Run() /// protected virtual void HandleMergeException(Exception exc) { - //try - //{ // When an exception is hit during merge, IndexWriter // removes any partial files and then allows another // merge to run. If whatever caused the error is not @@ -704,12 +697,8 @@ protected virtual void HandleMergeException(Exception exc) // so, we sleep here to avoid saturating CPU in such // cases: Thread.Sleep(250); - //} - //catch (ThreadInterruptedException ie) // LUCENENET NOTE: Senseless to catch and rethrow the same exception type - //{ - // throw new ThreadInterruptedException("Thread Interrupted Exception", ie); - //} throw new MergePolicy.MergeException(exc, m_dir); + // LUCENENET NOTE: No need to catch and rethrow same excepton type ThreadInterruptedException } private bool suppressExceptions; diff --git a/src/Lucene.Net/Index/DirectoryReader.cs b/src/Lucene.Net/Index/DirectoryReader.cs index 9de6f4f819..f8f46ef297 100644 --- a/src/Lucene.Net/Index/DirectoryReader.cs +++ b/src/Lucene.Net/Index/DirectoryReader.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.IO; @@ -296,25 +296,7 @@ public static IList ListCommits(Directory dir) // segments_N is corrupt sis.Read(dir, fileName); } - catch (FileNotFoundException) - { - // LUCENE-948: on NFS (and maybe others), if - // you have writers switching back and forth - // between machines, it's very likely that the - // dir listing will be stale and will claim a - // file segments_X exists when in fact it - // doesn't. So, we catch this and handle it - // as if the file does not exist - sis = null; - } - // LUCENENET specific - .NET (thankfully) only has one FileNotFoundException, so we don't need this - //catch (NoSuchFileException) - //{ - // sis = null; - //} - // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException - // in Lucene, we need to catch it here to be on the safe side. - catch (DirectoryNotFoundException) + catch (Exception fnfe) when (fnfe.IsNoSuchFileExceptionOrFileNotFoundException()) { // LUCENE-948: on NFS (and maybe others), if // you have writers switching back and forth @@ -365,7 +347,7 @@ public static bool IndexExists(Directory directory) { files = directory.ListAll(); } - catch (DirectoryNotFoundException /*nsde*/) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception nsde) when (nsde.IsNoSuchDirectoryException()) { // Directory does not exist --> no index exists return false; diff --git a/src/Lucene.Net/Index/DocFieldProcessor.cs b/src/Lucene.Net/Index/DocFieldProcessor.cs index 5d4377db8b..8d493da097 100644 --- a/src/Lucene.Net/Index/DocFieldProcessor.cs +++ b/src/Lucene.Net/Index/DocFieldProcessor.cs @@ -1,8 +1,9 @@ -using J2N.Text; +using J2N.Text; using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Index @@ -107,7 +108,7 @@ public override void Abort() { fieldNext.Abort(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (th == null) { @@ -122,7 +123,7 @@ public override void Abort() { storedConsumer.Abort(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (th == null) { @@ -134,7 +135,7 @@ public override void Abort() { consumer.Abort(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (th == null) { @@ -145,12 +146,10 @@ public override void Abort() // If any errors occured, throw it. if (th != null) { - if (th is Exception e) - { - throw e; - } + if (th.IsRuntimeException()) ExceptionDispatchInfo.Capture(th).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw + if (th.IsError()) ExceptionDispatchInfo.Capture(th).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw // defensive code - we should not hit unchecked exceptions - throw new Exception(th.Message, th); + throw RuntimeException.Create(th); } } diff --git a/src/Lucene.Net/Index/DocInverterPerField.cs b/src/Lucene.Net/Index/DocInverterPerField.cs index a66617b24c..97e91f3bbe 100644 --- a/src/Lucene.Net/Index/DocInverterPerField.cs +++ b/src/Lucene.Net/Index/DocInverterPerField.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Analysis.TokenAttributes; +using Lucene.Net.Analysis.TokenAttributes; using System; using System.Runtime.CompilerServices; @@ -83,7 +83,7 @@ public override void ProcessFields(IIndexableField[] fields, int count) // if the field omits norms, the boost cannot be indexed. if (fieldType.OmitNorms && field.Boost != 1.0f) { - throw new NotSupportedException("You cannot set an index-time boost: norms are omitted for field '" + field.Name + "'"); + throw UnsupportedOperationException.Create("You cannot set an index-time boost: norms are omitted for field '" + field.Name + "'"); } // only bother checking offsets if something will consume them. diff --git a/src/Lucene.Net/Index/DocTermOrds.cs b/src/Lucene.Net/Index/DocTermOrds.cs index 891f5928ff..61b384f7e3 100644 --- a/src/Lucene.Net/Index/DocTermOrds.cs +++ b/src/Lucene.Net/Index/DocTermOrds.cs @@ -331,7 +331,7 @@ protected virtual void Uninvert(AtomicReader reader, IBits liveDocs, BytesRef te FieldInfo info = reader.FieldInfos.FieldInfo(m_field); if (info != null && info.HasDocValues) { - throw new InvalidOperationException("Type mismatch: " + m_field + " was indexed as " + info.DocValuesType); + throw IllegalStateException.Create("Type mismatch: " + m_field + " was indexed as " + info.DocValuesType); } //System.out.println("DTO uninvert field=" + field + " prefix=" + termPrefix); long startTime = Environment.TickCount; @@ -412,7 +412,7 @@ protected virtual void Uninvert(AtomicReader reader, IBits liveDocs, BytesRef te m_ordBase = (int)te.Ord; //System.out.println("got ordBase=" + ordBase); } - catch (NotSupportedException) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception uoe) when (uoe.IsUnsupportedOperationException()) { // Reader cannot provide ord support, so we wrap // our own support by creating our own terms index: @@ -604,7 +604,7 @@ protected virtual void Uninvert(AtomicReader reader, IBits liveDocs, BytesRef te if ((pos & 0xff000000) != 0) { // we only have 24 bits for the array index - throw new InvalidOperationException("Too many values for UnInvertedField faceting on field " + m_field); + throw IllegalStateException.Create("Too many values for UnInvertedField faceting on field " + m_field); } var arr = bytes[doc]; /* @@ -1068,9 +1068,9 @@ public override void LookupOrd(long ord, BytesRef result) { @ref = outerInstance.LookupTerm(te, (int)ord); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } result.Bytes = @ref.Bytes; result.Offset = @ref.Offset; @@ -1092,9 +1092,9 @@ public override long LookupTerm(BytesRef key) return -te.Ord - 1; } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } @@ -1104,11 +1104,9 @@ public override TermsEnum GetTermsEnum() { return outerInstance.GetOrdTermsEnum(reader); } -#pragma warning disable 168 - catch (IOException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } } diff --git a/src/Lucene.Net/Index/DocValuesProcessor.cs b/src/Lucene.Net/Index/DocValuesProcessor.cs index 3b71a8aeb7..8841103b6e 100644 --- a/src/Lucene.Net/Index/DocValuesProcessor.cs +++ b/src/Lucene.Net/Index/DocValuesProcessor.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using Lucene.Net.Documents.Extensions; using System; @@ -225,7 +225,7 @@ public override void Abort() { writer.Abort(); } - catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception t) when (t.IsThrowable()) { // ignore } diff --git a/src/Lucene.Net/Index/DocumentsWriter.cs b/src/Lucene.Net/Index/DocumentsWriter.cs index 587a461f0b..2bbde1508a 100644 --- a/src/Lucene.Net/Index/DocumentsWriter.cs +++ b/src/Lucene.Net/Index/DocumentsWriter.cs @@ -1,4 +1,4 @@ -using J2N.Threading.Atomic; +using J2N.Threading.Atomic; using Lucene.Net.Diagnostics; using System; using System.Collections.Concurrent; @@ -229,7 +229,7 @@ private void EnsureOpen() { if (closed) { - throw new ObjectDisposedException(this.GetType().FullName, "this IndexWriter is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this IndexWriter is disposed."); } } diff --git a/src/Lucene.Net/Index/DocumentsWriterDeleteQueue.cs b/src/Lucene.Net/Index/DocumentsWriterDeleteQueue.cs index 5be829ac7d..e378aea6ed 100644 --- a/src/Lucene.Net/Index/DocumentsWriterDeleteQueue.cs +++ b/src/Lucene.Net/Index/DocumentsWriterDeleteQueue.cs @@ -375,7 +375,7 @@ internal Node(object item) internal virtual void Apply(BufferedUpdates bufferedDeletes, int docIDUpto) { - throw new InvalidOperationException("sentinel item must never be applied"); + throw IllegalStateException.Create("sentinel item must never be applied"); } internal virtual bool CasNext(Node cmp, Node val) diff --git a/src/Lucene.Net/Index/DocumentsWriterFlushControl.cs b/src/Lucene.Net/Index/DocumentsWriterFlushControl.cs index cdd85b36e8..8a23eacdde 100644 --- a/src/Lucene.Net/Index/DocumentsWriterFlushControl.cs +++ b/src/Lucene.Net/Index/DocumentsWriterFlushControl.cs @@ -539,7 +539,7 @@ public bool MoveNext() public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } @@ -820,7 +820,7 @@ internal void AbortPendingFlushes(ISet newFiles) documentsWriter.SubtractFlushedNumDocs(dwpt.NumDocsInRAM); dwpt.Abort(newFiles); } - catch (Exception) + catch (Exception ex) when (ex.IsThrowable()) { // ignore - keep on aborting the flush queue } @@ -837,7 +837,7 @@ internal void AbortPendingFlushes(ISet newFiles) documentsWriter.SubtractFlushedNumDocs(blockedFlush.Dwpt.NumDocsInRAM); blockedFlush.Dwpt.Abort(newFiles); } - catch (Exception) + catch (Exception ex) when (ex.IsThrowable()) { // ignore - keep on aborting the blocked queue } diff --git a/src/Lucene.Net/Index/DocumentsWriterPerThread.cs b/src/Lucene.Net/Index/DocumentsWriterPerThread.cs index e54ca15cca..e8029e3e94 100644 --- a/src/Lucene.Net/Index/DocumentsWriterPerThread.cs +++ b/src/Lucene.Net/Index/DocumentsWriterPerThread.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Util; using System; using System.Collections.Generic; @@ -175,7 +175,7 @@ internal virtual void Abort(ISet createdFiles) { consumer.Abort(); } - catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception t) when (t.IsThrowable()) { // ignore } diff --git a/src/Lucene.Net/Index/DocumentsWriterPerThreadPool.cs b/src/Lucene.Net/Index/DocumentsWriterPerThreadPool.cs index 5cdd2f1f40..10240f8b97 100644 --- a/src/Lucene.Net/Index/DocumentsWriterPerThreadPool.cs +++ b/src/Lucene.Net/Index/DocumentsWriterPerThreadPool.cs @@ -165,7 +165,7 @@ internal DocumentsWriterPerThreadPool(int maxNumThreadStates) { if (maxNumThreadStates < 1) { - throw new ArgumentException("maxNumThreadStates must be >= 1 but was: " + maxNumThreadStates); + throw new ArgumentOutOfRangeException(nameof(maxNumThreadStates), "maxNumThreadStates must be >= 1 but was: " + maxNumThreadStates); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } threadStates = new ThreadState[maxNumThreadStates]; numThreadStatesActive = 0; @@ -181,7 +181,7 @@ public object Clone() // We should only be cloned before being used: if (numThreadStatesActive != 0) { - throw new InvalidOperationException("clone this object before it is used!"); + throw IllegalStateException.Create("clone this object before it is used!"); } return new DocumentsWriterPerThreadPool(threadStates.Length); } @@ -351,6 +351,7 @@ public ThreadState GetAndLock(/* Thread requestingThread, DocumentsWriter docume { // Wait until a thread state frees up: Monitor.Wait(this); + // LUCENENET NOTE: No need to catch and rethrow same excepton type ThreadInterruptedException } } } diff --git a/src/Lucene.Net/Index/FieldInfos.cs b/src/Lucene.Net/Index/FieldInfos.cs index 7ff08ad118..9283d06a54 100644 --- a/src/Lucene.Net/Index/FieldInfos.cs +++ b/src/Lucene.Net/Index/FieldInfos.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using System; using System.Collections; @@ -175,7 +175,7 @@ public virtual FieldInfo FieldInfo(int fieldNumber) { if (fieldNumber < 0) { - throw new ArgumentException("Illegal field number: " + fieldNumber); + throw new ArgumentOutOfRangeException(nameof(fieldNumber), "Illegal field number: " + fieldNumber); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } byNumber.TryGetValue(fieldNumber, out FieldInfo ret); return ret; diff --git a/src/Lucene.Net/Index/FilteredTermsEnum.cs b/src/Lucene.Net/Index/FilteredTermsEnum.cs index f41fc441b5..0938130ff0 100644 --- a/src/Lucene.Net/Index/FilteredTermsEnum.cs +++ b/src/Lucene.Net/Index/FilteredTermsEnum.cs @@ -160,7 +160,7 @@ protected virtual BytesRef NextSeekTerm(BytesRef currentTerm) /// support seeking. public override bool SeekExact(BytesRef term) { - throw new NotSupportedException(this.GetType().Name + " does not support seeking"); + throw UnsupportedOperationException.Create(this.GetType().Name + " does not support seeking"); } /// @@ -169,7 +169,7 @@ public override bool SeekExact(BytesRef term) /// support seeking. public override SeekStatus SeekCeil(BytesRef term) { - throw new NotSupportedException(this.GetType().Name + " does not support seeking"); + throw UnsupportedOperationException.Create(this.GetType().Name + " does not support seeking"); } /// @@ -178,7 +178,7 @@ public override SeekStatus SeekCeil(BytesRef term) /// support seeking. public override void SeekExact(long ord) { - throw new NotSupportedException(this.GetType().Name + " does not support seeking"); + throw UnsupportedOperationException.Create(this.GetType().Name + " does not support seeking"); } public override long Ord => tenum.Ord; @@ -199,7 +199,7 @@ public override DocsAndPositionsEnum DocsAndPositions(IBits bits, DocsAndPositio /// support seeking. public override void SeekExact(BytesRef term, TermState state) { - throw new NotSupportedException(this.GetType().Name + " does not support seeking"); + throw UnsupportedOperationException.Create(this.GetType().Name + " does not support seeking"); } /// diff --git a/src/Lucene.Net/Index/FrozenBufferedUpdates.cs b/src/Lucene.Net/Index/FrozenBufferedUpdates.cs index 3a242f3862..8c66984ca0 100644 --- a/src/Lucene.Net/Index/FrozenBufferedUpdates.cs +++ b/src/Lucene.Net/Index/FrozenBufferedUpdates.cs @@ -232,7 +232,7 @@ public virtual bool MoveNext() public virtual void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public void Dispose() diff --git a/src/Lucene.Net/Index/IndexCommit.cs b/src/Lucene.Net/Index/IndexCommit.cs index c49cff630b..3caabec528 100644 --- a/src/Lucene.Net/Index/IndexCommit.cs +++ b/src/Lucene.Net/Index/IndexCommit.cs @@ -127,7 +127,7 @@ public virtual int CompareTo(IndexCommit commit) { if (Directory != commit.Directory) { - throw new NotSupportedException("cannot compare IndexCommits from different Directory instances"); + throw UnsupportedOperationException.Create("cannot compare IndexCommits from different Directory instances"); } long gen = Generation; diff --git a/src/Lucene.Net/Index/IndexFileDeleter.cs b/src/Lucene.Net/Index/IndexFileDeleter.cs index fd52c455cf..b10bd831fa 100644 --- a/src/Lucene.Net/Index/IndexFileDeleter.cs +++ b/src/Lucene.Net/Index/IndexFileDeleter.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -151,7 +151,7 @@ public IndexFileDeleter(Directory directory, IndexDeletionPolicy policy, Segment { files = directory.ListAll(); } - catch (DirectoryNotFoundException) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception e) when (e.IsNoSuchDirectoryException()) { // it means the directory is empty, so ignore it. files = Arrays.Empty(); @@ -182,9 +182,7 @@ public IndexFileDeleter(Directory directory, IndexDeletionPolicy policy, Segment { sis.Read(directory, fileName); } -#pragma warning disable 168 - catch (FileNotFoundException e) -#pragma warning restore 168 + catch (Exception e) when (e.IsNoSuchFileExceptionOrFileNotFoundException()) { // LUCENE-948: on NFS (and maybe others), if // you have writers switching back and forth @@ -199,40 +197,7 @@ public IndexFileDeleter(Directory directory, IndexDeletionPolicy policy, Segment } sis = null; } - // LUCENENET specific - .NET (thankfully) only has one FileNotFoundException, so we don't need this - //catch (NoSuchFileException) - //{ - // // LUCENE-948: on NFS (and maybe others), if - // // you have writers switching back and forth - // // between machines, it's very likely that the - // // dir listing will be stale and will claim a - // // file segments_X exists when in fact it - // // doesn't. So, we catch this and handle it - // // as if the file does not exist - // if (infoStream.IsEnabled("IFD")) - // { - // infoStream.Message("IFD", "init: hit FileNotFoundException when loading commit \"" + fileName + "\"; skipping this commit point"); - // } - // sis = null; - //} - // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException - // in Lucene, we need to catch it here to be on the safe side. - catch (DirectoryNotFoundException) - { - // LUCENE-948: on NFS (and maybe others), if - // you have writers switching back and forth - // between machines, it's very likely that the - // dir listing will be stale and will claim a - // file segments_X exists when in fact it - // doesn't. So, we catch this and handle it - // as if the file does not exist - if (infoStream.IsEnabled("IFD")) - { - infoStream.Message("IFD", "init: hit FileNotFoundException when loading commit \"" + fileName + "\"; skipping this commit point"); - } - sis = null; - } - catch (IOException /*e*/) + catch (Exception e) when (e.IsIOException()) { if (SegmentInfos.GenerationFromSegmentsFileName(fileName) <= currentGen && directory.FileLength(fileName) > 0) { @@ -280,7 +245,7 @@ public IndexFileDeleter(Directory directory, IndexDeletionPolicy policy, Segment { sis.Read(directory, currentSegmentsFile); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { throw new CorruptIndexException("failed to locate current segments_N file \"" + currentSegmentsFile + "\"" + e.ToString(), e); } @@ -330,7 +295,7 @@ private void EnsureOpen() { if (writer == null) { - throw new ObjectDisposedException(this.GetType().FullName, "this IndexWriter is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this IndexWriter is disposed."); } else { @@ -715,7 +680,7 @@ internal void DeleteFile(string fileName) } directory.DeleteFile(fileName); } // if delete fails - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { // Some operating systems (e.g. Windows) don't // permit a file to be deleted while it is opened diff --git a/src/Lucene.Net/Index/IndexFormatTooNewException.cs b/src/Lucene.Net/Index/IndexFormatTooNewException.cs index 27ed51caee..ef04db4b1c 100644 --- a/src/Lucene.Net/Index/IndexFormatTooNewException.cs +++ b/src/Lucene.Net/Index/IndexFormatTooNewException.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; #if FEATURE_SERIALIZABLE_EXCEPTIONS using System.Runtime.Serialization; @@ -65,13 +65,13 @@ public IndexFormatTooNewException(DataInput input, int version, int minVersion, { } -#if FEATURE_SERIALIZABLE_EXCEPTIONS - // For testing purposes - public IndexFormatTooNewException(string message) + // LUCENENET: For testing purposes + internal IndexFormatTooNewException(string message) : base(message) { } +#if FEATURE_SERIALIZABLE_EXCEPTIONS /// /// Initializes a new instance of this class with serialized data. /// diff --git a/src/Lucene.Net/Index/IndexFormatTooOldException.cs b/src/Lucene.Net/Index/IndexFormatTooOldException.cs index fb29d777a8..25cb849e4c 100644 --- a/src/Lucene.Net/Index/IndexFormatTooOldException.cs +++ b/src/Lucene.Net/Index/IndexFormatTooOldException.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; #if FEATURE_SERIALIZABLE_EXCEPTIONS using System.Runtime.Serialization; @@ -90,13 +90,13 @@ public IndexFormatTooOldException(DataInput input, int version, int minVersion, { } -#if FEATURE_SERIALIZABLE_EXCEPTIONS - // For testing purposes - public IndexFormatTooOldException(string message) + // LUCENENET: For testing purposes + internal IndexFormatTooOldException(string message) : base(message) { } +#if FEATURE_SERIALIZABLE_EXCEPTIONS /// /// Initializes a new instance of this class with serialized data. /// diff --git a/src/Lucene.Net/Index/IndexReader.cs b/src/Lucene.Net/Index/IndexReader.cs index 651bd52bfe..d97842f02c 100644 --- a/src/Lucene.Net/Index/IndexReader.cs +++ b/src/Lucene.Net/Index/IndexReader.cs @@ -1,4 +1,4 @@ -using J2N.Threading.Atomic; +using J2N.Threading.Atomic; using Lucene.Net.Documents; using Lucene.Net.Support; using Lucene.Net.Util; @@ -81,7 +81,7 @@ internal IndexReader() { if (!(this is CompositeReader || this is AtomicReader)) { - throw new Exception("IndexReader should never be directly extended, subclass AtomicReader or CompositeReader instead."); + throw Error.Create("IndexReader should never be directly extended, subclass AtomicReader or CompositeReader instead."); } } @@ -149,7 +149,7 @@ private void NotifyReaderClosedListeners(Exception th) { listener.OnClose(this); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (th == null) { @@ -266,7 +266,7 @@ public void DecRef() // still close the reader if it was made invalid by a child: if (refCount <= 0) { - throw new ObjectDisposedException(this.GetType().FullName, "this IndexReader is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this IndexReader is disposed."); } int rc = refCount.DecrementAndGet(); @@ -278,7 +278,7 @@ public void DecRef() { DoClose(); } - catch (Exception th) + catch (Exception th) when (th.IsThrowable()) { throwable = th; } @@ -296,7 +296,7 @@ public void DecRef() } else if (rc < 0) { - throw new InvalidOperationException("too many decRef calls: refCount is " + rc + " after decrement"); + throw IllegalStateException.Create("too many decRef calls: refCount is " + rc + " after decrement"); } } @@ -309,13 +309,13 @@ protected internal void EnsureOpen() { if (refCount <= 0) { - throw new ObjectDisposedException(this.GetType().FullName, "this IndexReader is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this IndexReader is disposed."); } // the happens before rule on reading the refCount, which must be after the fake write, // ensures that we see the value: if (closedByChild) { - throw new ObjectDisposedException(this.GetType().FullName, "this IndexReader cannot be used anymore as one of its child readers was closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this IndexReader cannot be used anymore as one of its child readers was disposed."); } } diff --git a/src/Lucene.Net/Index/IndexReaderContext.cs b/src/Lucene.Net/Index/IndexReaderContext.cs index 023b5c5088..907bdffa76 100644 --- a/src/Lucene.Net/Index/IndexReaderContext.cs +++ b/src/Lucene.Net/Index/IndexReaderContext.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace Lucene.Net.Index @@ -46,7 +46,7 @@ internal IndexReaderContext(CompositeReaderContext parent, int ordInParent, int { if (!(this is CompositeReaderContext || this is AtomicReaderContext)) { - throw new Exception("this class should never be extended by custom code!"); + throw Error.Create("this class should never be extended by custom code!"); } this.Parent = parent; this.DocBaseInParent = docBaseInParent; diff --git a/src/Lucene.Net/Index/IndexWriter.cs b/src/Lucene.Net/Index/IndexWriter.cs index 637da362e5..362a6b1abc 100644 --- a/src/Lucene.Net/Index/IndexWriter.cs +++ b/src/Lucene.Net/Index/IndexWriter.cs @@ -10,6 +10,7 @@ using System.Globalization; using System.IO; using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using JCG = J2N.Collections.Generic; @@ -397,9 +398,9 @@ public virtual DirectoryReader GetReader(bool applyAllDeletes) } } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "getReader"); + HandleOOM(oom, "GetReader"); // never reached but javac disagrees: return null; } @@ -584,7 +585,7 @@ internal virtual void DropAll(bool doSave) outerInstance.CheckpointNoSIS(); // Throws IOException } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (doSave) { @@ -611,7 +612,7 @@ internal virtual void DropAll(bool doSave) { rld.DropReaders(); // Throws IOException } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (doSave) { @@ -670,7 +671,7 @@ public virtual ReadersAndUpdates Get(SegmentCommitInfo info, bool create) { lock (this) { - if (Debugging.AssertsEnabled) Debugging.Assert(info.Info.Dir == outerInstance.directory,"info.dir={0} vs {1}", info.Info.Dir, outerInstance.directory); + if (Debugging.AssertsEnabled) Debugging.Assert(info.Info.Dir == outerInstance.directory, "info.dir={0} vs {1}", info.Info.Dir, outerInstance.directory); if (!readerMap.TryGetValue(info, out ReadersAndUpdates rld) || rld == null) { @@ -685,7 +686,7 @@ public virtual ReadersAndUpdates Get(SegmentCommitInfo info, bool create) else { if (Debugging.AssertsEnabled && !(rld.Info == info)) - throw new AssertionException(string.Format("rld.info={0} info={1} isLive?={2} vs {3}", rld.Info, info, InfoIsLive(rld.Info),InfoIsLive(info))); + throw AssertionError.Create(string.Format("rld.info={0} info={1} isLive?={2} vs {3}", rld.Info, info, InfoIsLive(rld.Info), InfoIsLive(info))); } if (create) @@ -748,7 +749,7 @@ protected internal void EnsureOpen(bool failIfDisposing) { if (closed || (failIfDisposing && closing)) { - throw new ObjectDisposedException(this.GetType().FullName, "this IndexWriter is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this IndexWriter is disposed."); } } @@ -848,7 +849,7 @@ public IndexWriter(Directory d, IndexWriterConfig conf) segmentInfos.Read(directory); segmentInfos.Clear(); } - catch (IOException) + catch (Exception e) when (e.IsIOException()) { // Likely this means it's a fresh directory initialIndexExists = false; @@ -1133,7 +1134,7 @@ private void CloseInternal(bool waitForMerges, bool doFlush) { if (pendingCommit != null) { - throw new InvalidOperationException("cannot close: prepareCommit was already called with no corresponding call to commit"); + throw IllegalStateException.Create("cannot close: prepareCommit was already called with no corresponding call to commit"); } if (infoStream.IsEnabled("IW")) @@ -1171,7 +1172,7 @@ private void CloseInternal(bool waitForMerges, bool doFlush) // any pending merges are waiting: mergeScheduler.Merge(this, MergeTrigger.CLOSING, false); } - catch (ThreadInterruptedException) + catch (ThreadInterruptedException) // LUCENENET: In Lucene, they caught their custom ThreadInterruptedException here, so we are leaving this catch block as is { // ignore any interruption, does not matter interrupted = true; @@ -1191,7 +1192,7 @@ private void CloseInternal(bool waitForMerges, bool doFlush) FinishMerges(waitForMerges && !interrupted); break; } - catch (ThreadInterruptedException) + catch (ThreadInterruptedException) // LUCENENET: In Lucene, they caught their custom ThreadInterruptedException here, so we are leaving this catch block as is { // by setting the interrupted status, the // next call to finishMerges will pass false, @@ -1253,9 +1254,9 @@ private void CloseInternal(bool waitForMerges, bool doFlush) Debugging.Assert(numDeactivatedThreadStates == docWriter.perThreadPool.MaxThreadStates, "{0} {1}", numDeactivatedThreadStates, docWriter.perThreadPool.MaxThreadStates); } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "closeInternal"); + HandleOOM(oom, "CloseInternal"); } finally { @@ -1550,9 +1551,9 @@ public virtual void UpdateDocuments(Term delTerm, IEnumerable doc, } } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "updateDocument"); + HandleOOM(oom, "UpdateDocument"); } } @@ -1864,9 +1865,9 @@ public virtual void UpdateNumericDocValue(Term term, string field, long? value) ProcessEvents(true, false); } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "updateNumericDocValue"); + HandleOOM(oom, "UpdateNumericDocValue"); } } @@ -1910,9 +1911,9 @@ public virtual void UpdateBinaryDocValue(Term term, string field, BytesRef value ProcessEvents(true, false); } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "updateBinaryDocValue"); + HandleOOM(oom, "UpdateBinaryDocValue"); } } @@ -2081,7 +2082,7 @@ public virtual void ForceMerge(int maxNumSegments, bool doWait) if (maxNumSegments < 1) { - throw new ArgumentException("maxNumSegments must be >= 1; got " + maxNumSegments); + throw new ArgumentOutOfRangeException(nameof(maxNumSegments), "maxNumSegments must be >= 1; got " + maxNumSegments); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (infoStream.IsEnabled("IW")) @@ -2127,7 +2128,7 @@ public virtual void ForceMerge(int maxNumSegments, bool doWait) { if (hitOOM) { - throw new InvalidOperationException("this writer hit an OutOfMemoryError; cannot complete forceMerge"); + throw IllegalStateException.Create("this writer hit an OutOfMemoryError; cannot complete forceMerge"); } if (mergeExceptions.Count > 0) @@ -2258,7 +2259,7 @@ public virtual void ForceMergeDeletes(bool doWait) { if (hitOOM) { - throw new InvalidOperationException("this writer hit an OutOfMemoryError; cannot complete forceMergeDeletes"); + throw IllegalStateException.Create("this writer hit an OutOfMemoryError; cannot complete forceMergeDeletes"); } // Check each merge that MergePolicy asked us to @@ -2565,9 +2566,9 @@ private void RollbackInternal() success = true; } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "rollbackInternal"); + HandleOOM(oom, "RollbackInternal"); } finally { @@ -2592,7 +2593,7 @@ private void RollbackInternal() pendingCommit.RollbackCommit(directory); deleter.DecRef(pendingCommit); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { } } @@ -2676,9 +2677,9 @@ public virtual void DeleteAll() globalFieldNumberMap.Clear(); success = true; } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "deleteAll"); + HandleOOM(oom, "DeleteAll"); } finally { @@ -3066,7 +3067,7 @@ public virtual void AddIndexes(params Directory[] dirs) { directory.DeleteFile(file); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { } } @@ -3094,7 +3095,7 @@ public virtual void AddIndexes(params Directory[] dirs) { directory.DeleteFile(file); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { } } @@ -3107,9 +3108,9 @@ public virtual void AddIndexes(params Directory[] dirs) successTop = true; } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "addIndexes(Directory...)"); + HandleOOM(oom, "AddIndexes(Directory...)"); } finally { @@ -3294,9 +3295,9 @@ public virtual void AddIndexes(params IndexReader[] readers) Checkpoint(); } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "addIndexes(IndexReader...)"); + HandleOOM(oom, "AddIndexes(IndexReader...)"); } } @@ -3377,7 +3378,7 @@ private SegmentCommitInfo CopySegmentAsIs(SegmentCommitInfo info, string segName { currentCodec.SegmentInfoFormat.SegmentInfoWriter.Write(trackingDir, newInfo, fis, context); } - catch (NotSupportedException /*uoe*/) + catch (Exception uoe) when (uoe.IsUnsupportedOperationException()) { #pragma warning disable 612, 618 if (currentCodec is Lucene3xCodec) @@ -3441,7 +3442,7 @@ private SegmentCommitInfo CopySegmentAsIs(SegmentCommitInfo info, string segName { directory.DeleteFile(file); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { } } @@ -3506,12 +3507,12 @@ private void PrepareCommitInternal() if (hitOOM) { - throw new InvalidOperationException("this writer hit an OutOfMemoryError; cannot commit"); + throw IllegalStateException.Create("this writer hit an OutOfMemoryError; cannot commit"); } if (pendingCommit != null) { - throw new InvalidOperationException("prepareCommit was already called with no corresponding call to commit"); + throw IllegalStateException.Create("prepareCommit was already called with no corresponding call to commit"); } DoBeforeFlush(); @@ -3582,9 +3583,9 @@ private void PrepareCommitInternal() } } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "prepareCommit"); + HandleOOM(oom, "PrepareCommit"); } bool success_ = false; @@ -3824,7 +3825,7 @@ private bool DoFlush(bool applyAllDeletes) { if (hitOOM) { - throw new InvalidOperationException("this writer hit an OutOfMemoryError; cannot flush"); + throw IllegalStateException.Create("this writer hit an OutOfMemoryError; cannot flush"); } DoBeforeFlush(); @@ -3867,9 +3868,9 @@ private bool DoFlush(bool applyAllDeletes) return anySegmentFlushed; } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "doFlush"); + HandleOOM(oom, "DoFlush"); // never hit return false; } @@ -4305,7 +4306,7 @@ private bool CommitMerge(MergePolicy.OneMerge merge, MergeState mergeState) if (hitOOM) { - throw new InvalidOperationException("this writer hit an OutOfMemoryError; cannot complete merge"); + throw IllegalStateException.Create("this writer hit an OutOfMemoryError; cannot complete merge"); } if (infoStream.IsEnabled("IW")) @@ -4431,7 +4432,7 @@ private bool CommitMerge(MergePolicy.OneMerge merge, MergeState mergeState) { Checkpoint(); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // Ignore so we keep throwing original exception. } @@ -4481,7 +4482,7 @@ private void HandleMergeException(Exception t, MergePolicy.OneMerge merge) // executed. if (merge.isExternal) { - throw t; + ExceptionDispatchInfo.Capture(t).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } } else @@ -4523,7 +4524,7 @@ public virtual void Merge(MergePolicy.OneMerge merge) MergeSuccess(merge); success = true; } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { HandleMergeException(t, merge); } @@ -4556,9 +4557,9 @@ public virtual void Merge(MergePolicy.OneMerge merge) } } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "merge"); + HandleOOM(oom, "Merge"); } if (merge.info != null && !merge.IsAborted) { @@ -4734,7 +4735,7 @@ private void MergeInitImpl(MergePolicy.OneMerge merge) // LUCENENET specific: re if (hitOOM) { - throw new InvalidOperationException("this writer hit an OutOfMemoryError; cannot merge"); + throw IllegalStateException.Create("this writer hit an OutOfMemoryError; cannot merge"); } if (merge.info != null) @@ -4892,7 +4893,7 @@ private void CloseMergeReaders(MergePolicy.OneMerge merge, bool suppressExceptio readerPool.Drop(rld.Info); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (th == null) { @@ -5090,7 +5091,7 @@ private int MergeMiddle(MergePolicy.OneMerge merge) filesToRemove = CreateCompoundFile(infoStream, directory, checkAbort, merge.info.Info, context); success = true; } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { lock (this) { @@ -5106,7 +5107,7 @@ private int MergeMiddle(MergePolicy.OneMerge merge) } } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { HandleMergeException(t, merge); } @@ -5404,7 +5405,7 @@ private void StartCommit(SegmentInfos toSync) if (hitOOM) { - throw new InvalidOperationException("this writer hit an OutOfMemoryError; cannot commit"); + throw IllegalStateException.Create("this writer hit an OutOfMemoryError; cannot commit"); } try @@ -5512,9 +5513,9 @@ private void StartCommit(SegmentInfos toSync) } } } - catch (OutOfMemoryException oom) + catch (Exception oom) when (oom.IsOutOfMemoryError()) { - HandleOOM(oom, "startCommit"); + HandleOOM(oom, "StartCommit"); } if (Debugging.AssertsEnabled) Debugging.Assert(TestPoint("finishStartCommit")); } @@ -5574,14 +5575,14 @@ protected IndexReaderWarmer() public abstract void Warm(AtomicReader reader); } - private void HandleOOM(OutOfMemoryException oom, string location) + private void HandleOOM(/*OutOfMemory*/Exception oom, string location) // LUCENENET: Our handler doesn't cast to OutOfMemoryException, so we need to widen the parameter to accept Exception { if (infoStream.IsEnabled("IW")) { infoStream.Message("IW", "hit OutOfMemoryError inside " + location); } hitOOM = true; - throw oom; + ExceptionDispatchInfo.Capture(oom).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } // Used only by assert for testing. Current points: @@ -5685,7 +5686,8 @@ internal static ICollection CreateCompoundFile(InfoStream infoStream, Di // Now merge all added files ICollection files = info.GetFiles(); CompoundFileDirectory cfsDir = new CompoundFileDirectory(directory, fileName, context, true); - IOException prior = null; + // LUCENENET: Ported changes to this method from 4.8.1 + bool success = false; try { foreach (string file in files) @@ -5693,37 +5695,30 @@ internal static ICollection CreateCompoundFile(InfoStream infoStream, Di directory.Copy(cfsDir, file, file, context); checkAbort.Work(directory.FileLength(file)); } - } - catch (IOException ex) - { - prior = ex; + success = true; } finally { - bool success = false; - try + if (success) { - IOUtils.DisposeWhileHandlingException(prior, cfsDir); - success = true; + IOUtils.Dispose(cfsDir); } - finally + else { - if (!success) + IOUtils.DisposeWhileHandlingException(cfsDir); + try + { + directory.DeleteFile(fileName); + } + catch (Exception t) when (t.IsThrowable()) + { + } + try + { + directory.DeleteFile(Lucene.Net.Index.IndexFileNames.SegmentFileName(info.Name, "", Lucene.Net.Index.IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION)); + } + catch (Exception t) when (t.IsThrowable()) { - try - { - directory.DeleteFile(fileName); - } - catch (Exception) - { - } - try - { - directory.DeleteFile(Lucene.Net.Index.IndexFileNames.SegmentFileName(info.Name, "", Lucene.Net.Index.IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION)); - } - catch (Exception) - { - } } } } @@ -5866,18 +5861,7 @@ private static bool SlowFileExists(Directory dir, string fileName) using (var input = dir.OpenInput(fileName, IOContext.DEFAULT)) { } 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; } diff --git a/src/Lucene.Net/Index/IndexWriterConfig.cs b/src/Lucene.Net/Index/IndexWriterConfig.cs index 726455283c..44d473cd01 100644 --- a/src/Lucene.Net/Index/IndexWriterConfig.cs +++ b/src/Lucene.Net/Index/IndexWriterConfig.cs @@ -237,7 +237,7 @@ public object Clone() new public IndexDeletionPolicy IndexDeletionPolicy { get => delPolicy; - set => delPolicy = value ?? throw new ArgumentNullException(nameof(value), "IndexDeletionPolicy must not be null"); + set => delPolicy = value ?? throw new ArgumentNullException(nameof(IndexDeletionPolicy), "IndexDeletionPolicy must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -266,7 +266,7 @@ public object Clone() new public Similarity Similarity { get => similarity; - set => similarity = value ?? throw new ArgumentNullException(nameof(value), "Similarity must not be null"); + set => similarity = value ?? throw new ArgumentNullException(nameof(Similarity), "Similarity must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -282,7 +282,7 @@ public object Clone() new public IMergeScheduler MergeScheduler { get => mergeScheduler; - set => mergeScheduler = value ?? throw new ArgumentNullException(nameof(value), "MergeScheduler must not be null"); + set => mergeScheduler = value ?? throw new ArgumentNullException(nameof(MergeScheduler), "MergeScheduler must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -310,7 +310,7 @@ public object Clone() new public Codec Codec { get => codec; - set => codec = value ?? throw new ArgumentException(nameof(value), "Codec must not be null"); + set => codec = value ?? throw new ArgumentNullException(nameof(Codec), "Codec must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -326,7 +326,7 @@ public object Clone() new public MergePolicy MergePolicy { get => mergePolicy; - set => mergePolicy = value ?? throw new ArgumentNullException(nameof(value), "MergePolicy must not be null"); + set => mergePolicy = value ?? throw new ArgumentNullException(nameof(MergePolicy), "MergePolicy must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -349,7 +349,7 @@ public object Clone() new internal DocumentsWriterPerThreadPool IndexerThreadPool { get => indexerThreadPool; - set => indexerThreadPool = value ?? throw new ArgumentNullException(nameof(value), "IndexerThreadPool must not be null"); + set => indexerThreadPool = value ?? throw new ArgumentNullException(nameof(IndexerThreadPool), "IndexerThreadPool must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -364,17 +364,8 @@ public object Clone() // so must declare it new. See: http://stackoverflow.com/q/82437 new public int MaxThreadStates { - get - { - try - { - return indexerThreadPool.MaxThreadStates; - } - catch (InvalidCastException cce) - { - throw new InvalidOperationException(cce.Message, cce); - } - } + // LUCENENET: Changes brought over from 4.8.1 mean there is no chance of a cast failure + get => indexerThreadPool.MaxThreadStates; set => this.indexerThreadPool = new DocumentsWriterPerThreadPool(value); } @@ -408,7 +399,7 @@ public object Clone() new internal IndexingChain IndexingChain { get => indexingChain; - set => indexingChain = value ?? throw new ArgumentNullException(nameof(value), "IndexingChain must not be null"); + set => indexingChain = value ?? throw new ArgumentNullException(nameof(IndexingChain), "IndexingChain must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -430,7 +421,7 @@ public object Clone() { if (value <= 0 || value >= 2048) { - throw new ArgumentException("PerThreadHardLimit must be greater than 0 and less than 2048MB"); + throw new ArgumentOutOfRangeException(nameof(RAMPerThreadHardLimitMB), "PerThreadHardLimit must be greater than 0 and less than 2048MB"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.perThreadHardLimitMB = value; } @@ -449,7 +440,7 @@ public object Clone() new internal FlushPolicy FlushPolicy { get => flushPolicy; - set => flushPolicy = value ?? throw new ArgumentNullException(nameof(value), "FlushPolicy must not be null"); + set => flushPolicy = value ?? throw new ArgumentNullException(nameof(FlushPolicy), "FlushPolicy must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } // LUCENENT NOTE: The following properties would be pointless, @@ -538,9 +529,9 @@ public IndexWriterConfig SetInfoStream(InfoStream infoStream) /// public IndexWriterConfig SetInfoStream(TextWriter printStream) { - if (printStream == null) + if (printStream is null) { - throw new ArgumentException("printStream must not be null"); + throw new ArgumentNullException("printStream must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } return SetInfoStream(new TextWriterInfoStream(printStream)); } diff --git a/src/Lucene.Net/Index/LiveIndexWriterConfig.cs b/src/Lucene.Net/Index/LiveIndexWriterConfig.cs index a4f8c630f4..d052dd4b69 100644 --- a/src/Lucene.Net/Index/LiveIndexWriterConfig.cs +++ b/src/Lucene.Net/Index/LiveIndexWriterConfig.cs @@ -289,7 +289,7 @@ public virtual int MaxBufferedDeleteTerms { if (value != IndexWriterConfig.DISABLE_AUTO_FLUSH && value < 1) { - throw new ArgumentException("maxBufferedDeleteTerms must at least be 1 when enabled"); + throw new ArgumentOutOfRangeException(nameof(MaxBufferedDeleteTerms), "maxBufferedDeleteTerms must at least be 1 when enabled"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.maxBufferedDeleteTerms = value; } @@ -348,7 +348,7 @@ public virtual double RAMBufferSizeMB { if (value != IndexWriterConfig.DISABLE_AUTO_FLUSH && value <= 0.0) { - throw new ArgumentException("ramBufferSizeMB should be > 0.0 MB when enabled"); + throw new ArgumentOutOfRangeException(nameof(RAMBufferSizeMB), "ramBufferSizeMB should be > 0.0 MB when enabled"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (value == IndexWriterConfig.DISABLE_AUTO_FLUSH && maxBufferedDocs == IndexWriterConfig.DISABLE_AUTO_FLUSH) { @@ -388,7 +388,7 @@ public virtual int MaxBufferedDocs { if (value != IndexWriterConfig.DISABLE_AUTO_FLUSH && value < 2) { - throw new ArgumentException("maxBufferedDocs must at least be 2 when enabled"); + throw new ArgumentOutOfRangeException(nameof(MaxBufferedDocs), "maxBufferedDocs must at least be 2 when enabled"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (value == IndexWriterConfig.DISABLE_AUTO_FLUSH && ramBufferSizeMB == IndexWriterConfig.DISABLE_AUTO_FLUSH) { @@ -432,7 +432,7 @@ public virtual int ReaderTermsIndexDivisor { if (value <= 0 && value != -1) { - throw new ArgumentException("divisor must be >= 1, or -1 (got " + value + ")"); + throw new ArgumentOutOfRangeException(nameof(ReaderTermsIndexDivisor), "divisor must be >= 1, or -1 (got " + value + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } readerTermsIndexDivisor = value; } @@ -494,20 +494,8 @@ public virtual int ReaderTermsIndexDivisor /// Returns the max number of simultaneous threads that may be indexing /// documents at once in . /// - public virtual int MaxThreadStates - { - get - { - try - { - return indexerThreadPool.MaxThreadStates; - } - catch (InvalidCastException cce) - { - throw new InvalidOperationException(cce.Message, cce); - } - } - } + // LUCENENET: Changes brought over from 4.8.1 mean there is no chance of a cast failure + public virtual int MaxThreadStates => indexerThreadPool.MaxThreadStates; /// /// Returns true if should pool readers even if diff --git a/src/Lucene.Net/Index/LogMergePolicy.cs b/src/Lucene.Net/Index/LogMergePolicy.cs index 98916dbe08..ca010af853 100644 --- a/src/Lucene.Net/Index/LogMergePolicy.cs +++ b/src/Lucene.Net/Index/LogMergePolicy.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -161,7 +161,7 @@ public virtual int MergeFactor { if (value < 2) { - throw new ArgumentException("mergeFactor cannot be less than 2"); + throw new ArgumentOutOfRangeException(nameof(MergeFactor), "mergeFactor cannot be less than 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.m_mergeFactor = value; } diff --git a/src/Lucene.Net/Index/MergePolicy.cs b/src/Lucene.Net/Index/MergePolicy.cs index bac428c095..cf6f5ac250 100644 --- a/src/Lucene.Net/Index/MergePolicy.cs +++ b/src/Lucene.Net/Index/MergePolicy.cs @@ -154,7 +154,7 @@ public OneMerge(IList segments) { if (0 == segments.Count) { - throw new Exception("segments must include at least one segment"); + throw RuntimeException.Create("segments must include at least one segment"); } // clone the list, as the in list may be based off original SegmentInfos and may be modified this.Segments = new List(segments); @@ -178,7 +178,7 @@ public virtual IList GetMergeReaders() { if (this.readers == null) { - throw new InvalidOperationException("IndexWriter has not initialized readers from the segment infos yet"); + throw IllegalStateException.Create("IndexWriter has not initialized readers from the segment infos yet"); } IList readers = new List(this.readers.Count); foreach (AtomicReader reader in this.readers) @@ -292,9 +292,9 @@ public virtual void CheckAborted(Directory dir) // do 1000 msec, defensively Monitor.Wait(this, TimeSpan.FromMilliseconds(1000)); } - catch (ThreadInterruptedException ie) + catch (Exception ie) when (ie.IsInterruptedException()) { - throw new Exception(ie.ToString(), ie); + throw RuntimeException.Create(ie); } if (aborted) @@ -456,7 +456,7 @@ public virtual string SegString(Directory dir) #if FEATURE_SERIALIZABLE_EXCEPTIONS [Serializable] #endif - public class MergeException : Exception + public class MergeException : Exception, IRuntimeException // LUCENENET specific: Added IRuntimeException for identification of the Java superclass in .NET { private readonly Directory dir; // LUCENENET: marked readonly @@ -476,13 +476,13 @@ public MergeException(Exception exc, Directory dir) this.dir = dir; } -#if FEATURE_SERIALIZABLE_EXCEPTIONS - // For testing purposes - public MergeException(string message) + // LUCENENET: For testing purposes + internal MergeException(string message) : base(message) { } +#if FEATURE_SERIALIZABLE_EXCEPTIONS /// /// Initializes a new instance of this class with serialized data. /// @@ -746,7 +746,7 @@ public double NoCFSRatio { if (value < 0.0 || value > 1.0) { - throw new ArgumentException("noCFSRatio must be 0.0 to 1.0 inclusive; got " + value); + throw new ArgumentOutOfRangeException(nameof(NoCFSRatio), "noCFSRatio must be 0.0 to 1.0 inclusive; got " + value); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.m_noCFSRatio = value; } @@ -768,7 +768,7 @@ public double MaxCFSSegmentSizeMB { if (value < 0.0) { - throw new ArgumentException("maxCFSSegmentSizeMB must be >=0 (got " + value + ")"); + throw new ArgumentOutOfRangeException(nameof(MaxCFSSegmentSizeMB), "maxCFSSegmentSizeMB must be >=0 (got " + value + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } value *= 1024 * 1024; this.m_maxCFSSegmentSize = (value > long.MaxValue) ? long.MaxValue : (long)value; diff --git a/src/Lucene.Net/Index/MultiReader.cs b/src/Lucene.Net/Index/MultiReader.cs index c0a1e32eda..acbdd1404e 100644 --- a/src/Lucene.Net/Index/MultiReader.cs +++ b/src/Lucene.Net/Index/MultiReader.cs @@ -1,4 +1,6 @@ +using System; using System.IO; +using System.Runtime.ExceptionServices; namespace Lucene.Net.Index { @@ -73,7 +75,7 @@ protected internal override void DoClose() { lock (this) { - IOException ioe = null; + Exception ioe = null; // LUCENENET: No need to cast to IOExcpetion foreach (IndexReader r in GetSequentialSubReaders()) { try @@ -87,7 +89,7 @@ protected internal override void DoClose() r.DecRef(); } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (ioe == null) { @@ -98,7 +100,7 @@ protected internal override void DoClose() // throw the first exception if (ioe != null) { - throw ioe; + ExceptionDispatchInfo.Capture(ioe).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } } } diff --git a/src/Lucene.Net/Index/MultiTerms.cs b/src/Lucene.Net/Index/MultiTerms.cs index 5843b865d6..d7167dd69d 100644 --- a/src/Lucene.Net/Index/MultiTerms.cs +++ b/src/Lucene.Net/Index/MultiTerms.cs @@ -72,7 +72,7 @@ public MultiTerms(Terms[] subs, ReaderSlice[] subSlices) IComparer subTermComp = subs[i].Comparer; if (subTermComp != null && !subTermComp.Equals(_termComp)) { - throw new InvalidOperationException("sub-readers have different BytesRef.Comparers; cannot merge"); + throw IllegalStateException.Create("sub-readers have different BytesRef.Comparers; cannot merge"); } } _hasFreqs &= subs[i].HasFreqs; diff --git a/src/Lucene.Net/Index/MultiTermsEnum.cs b/src/Lucene.Net/Index/MultiTermsEnum.cs index e007219d56..adedf215e9 100644 --- a/src/Lucene.Net/Index/MultiTermsEnum.cs +++ b/src/Lucene.Net/Index/MultiTermsEnum.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -129,7 +129,7 @@ public TermsEnum Reset(TermsEnumIndex[] termsEnumsIndex) IComparer subTermComp = termsEnumIndex.TermsEnum.Comparer; if (subTermComp != null && !subTermComp.Equals(termComp)) { - throw new InvalidOperationException("sub-readers have different BytesRef.Comparers: " + subTermComp + " vs " + termComp + "; cannot merge"); + throw IllegalStateException.Create("sub-readers have different BytesRef.Comparers: " + subTermComp + " vs " + termComp + "; cannot merge"); } } @@ -318,10 +318,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(); + public override long Ord => throw UnsupportedOperationException.Create(); private void PullTop() { diff --git a/src/Lucene.Net/Index/NumericDocValuesFieldUpdates.cs b/src/Lucene.Net/Index/NumericDocValuesFieldUpdates.cs index d4f47165bf..900b81477d 100644 --- a/src/Lucene.Net/Index/NumericDocValuesFieldUpdates.cs +++ b/src/Lucene.Net/Index/NumericDocValuesFieldUpdates.cs @@ -112,7 +112,7 @@ public override void Add(int doc, object value) // TODO: if the Sorter interface changes to take long indexes, we can remove that limitation if (size == int.MaxValue) { - throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries"); + throw IllegalStateException.Create("cannot support more than System.Int32.MaxValue doc/value entries"); } long? val = (long?)value; @@ -207,7 +207,7 @@ public override void Merge(DocValuesFieldUpdates other) NumericDocValuesFieldUpdates otherUpdates = (NumericDocValuesFieldUpdates)other; if (size + otherUpdates.size > int.MaxValue) { - throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries; size=" + size + " other.size=" + otherUpdates.size); + throw IllegalStateException.Create("cannot support more than System.Int32.MaxValue doc/value entries; size=" + size + " other.size=" + otherUpdates.size); } docs = docs.Grow(size + otherUpdates.size); values = values.Grow(size + otherUpdates.size); diff --git a/src/Lucene.Net/Index/NumericDocValuesWriter.cs b/src/Lucene.Net/Index/NumericDocValuesWriter.cs index 4941203659..6e13822e1c 100644 --- a/src/Lucene.Net/Index/NumericDocValuesWriter.cs +++ b/src/Lucene.Net/Index/NumericDocValuesWriter.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Util.Packed; +using Lucene.Net.Util.Packed; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; diff --git a/src/Lucene.Net/Index/ParallelAtomicReader.cs b/src/Lucene.Net/Index/ParallelAtomicReader.cs index 354e113075..d9db7802b3 100644 --- a/src/Lucene.Net/Index/ParallelAtomicReader.cs +++ b/src/Lucene.Net/Index/ParallelAtomicReader.cs @@ -1,8 +1,9 @@ -using J2N.Runtime.CompilerServices; +using J2N.Runtime.CompilerServices; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.IO; +using System.Runtime.ExceptionServices; using System.Text; using JCG = J2N.Collections.Generic; @@ -285,7 +286,7 @@ protected internal override void DoClose() { lock (this) { - IOException ioe = null; + Exception ioe = null; // LUCENENET: No need to cast to IOExcpetion foreach (AtomicReader reader in completeReaderSet) { try @@ -299,7 +300,7 @@ protected internal override void DoClose() reader.DecRef(); } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (ioe == null) { @@ -310,7 +311,7 @@ protected internal override void DoClose() // throw the first exception if (ioe != null) { - throw ioe; + ExceptionDispatchInfo.Capture(ioe).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } } } diff --git a/src/Lucene.Net/Index/ParallelCompositeReader.cs b/src/Lucene.Net/Index/ParallelCompositeReader.cs index 1bc75e2516..9ada68a175 100644 --- a/src/Lucene.Net/Index/ParallelCompositeReader.cs +++ b/src/Lucene.Net/Index/ParallelCompositeReader.cs @@ -1,9 +1,10 @@ -using J2N.Runtime.CompilerServices; +using J2N.Runtime.CompilerServices; using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.IO; +using System.Runtime.ExceptionServices; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Index @@ -223,7 +224,7 @@ protected internal override void DoClose() { lock (this) { - IOException ioe = null; + Exception ioe = null; // LUCENENET: No need to cast to IOExcpetion foreach (IndexReader reader in completeReaderSet) { try @@ -237,7 +238,7 @@ protected internal override void DoClose() reader.DecRef(); } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (ioe == null) { @@ -248,7 +249,7 @@ protected internal override void DoClose() // throw the first exception if (ioe != null) { - throw ioe; + ExceptionDispatchInfo.Capture(ioe).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } } } diff --git a/src/Lucene.Net/Index/PersistentSnapshotDeletionPolicy.cs b/src/Lucene.Net/Index/PersistentSnapshotDeletionPolicy.cs index 01acd85ac1..88a1e2ca77 100644 --- a/src/Lucene.Net/Index/PersistentSnapshotDeletionPolicy.cs +++ b/src/Lucene.Net/Index/PersistentSnapshotDeletionPolicy.cs @@ -1,9 +1,10 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; namespace Lucene.Net.Index { @@ -111,7 +112,7 @@ public PersistentSnapshotDeletionPolicy(IndexDeletionPolicy primary, Directory d if (mode == OpenMode.APPEND && nextWriteGen == 0) { - throw new InvalidOperationException("no snapshots stored in this directory"); + throw IllegalStateException.Create("no snapshots stored in this directory"); } } @@ -139,9 +140,7 @@ public override IndexCommit Snapshot() { base.Release(ic); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { // Suppress so we keep throwing original exception } @@ -175,9 +174,7 @@ public override void Release(IndexCommit commit) { IncRef(commit); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { // Suppress so we keep throwing original exception } @@ -229,9 +226,7 @@ internal void Persist() { dir.DeleteFile(fileName); } -#pragma warning disable 168 - catch (Exception e) -#pragma warning restore 168 + catch (Exception e) when (e.IsException()) { // Suppress so we keep throwing original exception } @@ -251,9 +246,7 @@ internal void Persist() { dir.DeleteFile(lastSaveFile); } -#pragma warning disable 168 - catch (IOException ioe) -#pragma warning restore 168 + catch (Exception ioe) when (ioe.IsIOException()) { // OK: likely it didn't exist } @@ -307,7 +300,7 @@ private void LoadPriorSnapshots() lock (this) { long genLoaded = -1; - IOException ioe = null; + Exception ioe = null; // LUCENENET: No need to cast to IOExcpetion IList snapshotFiles = new List(); foreach (string file in dir.ListAll()) { @@ -330,7 +323,7 @@ private void LoadPriorSnapshots() m[commitGen] = refCount; } } - catch (IOException ioe2) + catch (Exception ioe2) when (ioe2.IsIOException()) { // Save first exception & throw in the end if (ioe == null) @@ -356,7 +349,7 @@ private void LoadPriorSnapshots() if (ioe != null) { // ... not for lack of trying: - throw ioe; + ExceptionDispatchInfo.Capture(ioe).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } } else diff --git a/src/Lucene.Net/Index/PrefixCodedTerms.cs b/src/Lucene.Net/Index/PrefixCodedTerms.cs index 0b9deee14e..345415457a 100644 --- a/src/Lucene.Net/Index/PrefixCodedTerms.cs +++ b/src/Lucene.Net/Index/PrefixCodedTerms.cs @@ -1,4 +1,4 @@ -using J2N.Numerics; +using J2N.Numerics; using Lucene.Net.Diagnostics; using System; using System.Collections; @@ -76,9 +76,9 @@ internal PrefixCodedTermsIterator(RAMFile buffer) { input = new RAMInputStream("PrefixCodedTermsIterator", buffer); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } @@ -121,9 +121,9 @@ public virtual bool MoveNext() bytes.Length = prefix + suffix; term.Set(field, bytes); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } return true; @@ -133,7 +133,7 @@ public virtual bool MoveNext() public virtual void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } @@ -174,9 +174,9 @@ public virtual void Add(Term term) lastTerm.Bytes.CopyBytes(term.Bytes); lastTerm.Field = term.Field; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } } @@ -189,9 +189,9 @@ public virtual PrefixCodedTerms Finish() output.Dispose(); return new PrefixCodedTerms(buffer); } - 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/Index/ReadersAndUpdates.cs b/src/Lucene.Net/Index/ReadersAndUpdates.cs index 06ff9013f0..ad0f5a8fff 100644 --- a/src/Lucene.Net/Index/ReadersAndUpdates.cs +++ b/src/Lucene.Net/Index/ReadersAndUpdates.cs @@ -1,4 +1,4 @@ -using J2N.Threading.Atomic; +using J2N.Threading.Atomic; using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using System; @@ -440,7 +440,7 @@ public virtual bool WriteLiveDocs(Directory dir) { dir.DeleteFile(fileName); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // Ignore so we throw only the first exc } @@ -593,7 +593,7 @@ public virtual void WriteFieldUpdates(Directory dir, DocValuesFieldUpdates.Conta { dir.DeleteFile(fileName); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // Ignore so we throw only the first exc } diff --git a/src/Lucene.Net/Index/SegmentCommitInfo.cs b/src/Lucene.Net/Index/SegmentCommitInfo.cs index ad8868c531..e8a5fec42d 100644 --- a/src/Lucene.Net/Index/SegmentCommitInfo.cs +++ b/src/Lucene.Net/Index/SegmentCommitInfo.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -243,7 +243,7 @@ internal set { if (value < 0 || value > Info.DocCount) { - throw new ArgumentException("invalid delCount=" + value + " (docCount=" + Info.DocCount + ")"); + throw new ArgumentOutOfRangeException(nameof(DelCount), "invalid delCount=" + value + " (docCount=" + Info.DocCount + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.delCount = value; } diff --git a/src/Lucene.Net/Index/SegmentCoreReaders.cs b/src/Lucene.Net/Index/SegmentCoreReaders.cs index 4eacc17099..0a88cb716a 100644 --- a/src/Lucene.Net/Index/SegmentCoreReaders.cs +++ b/src/Lucene.Net/Index/SegmentCoreReaders.cs @@ -1,4 +1,4 @@ -using J2N.Threading.Atomic; +using J2N.Threading.Atomic; using Lucene.Net.Diagnostics; using Lucene.Net.Support; using Lucene.Net.Util; @@ -155,7 +155,7 @@ internal void IncRef() return; } } - throw new ObjectDisposedException(this.GetType().FullName, "SegmentCoreReaders is already closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "SegmentCoreReaders is already disposed."); } internal NumericDocValues GetNormValues(FieldInfo fi) @@ -182,7 +182,7 @@ internal void DecRef() { IOUtils.Dispose(termVectorsLocal, fieldsReaderLocal, normsLocal, fields, termVectorsReaderOrig, fieldsReaderOrig, cfsReader, normsProducer); } - catch (Exception throwable) + catch (Exception throwable) when (throwable.IsThrowable()) { th = throwable; } @@ -205,9 +205,8 @@ private void NotifyCoreClosedListeners(Exception th) { listener.OnDispose(this); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { - if (th == null) { th = t; diff --git a/src/Lucene.Net/Index/SegmentDocValues.cs b/src/Lucene.Net/Index/SegmentDocValues.cs index 4a6931e177..94b6b56d3f 100644 --- a/src/Lucene.Net/Index/SegmentDocValues.cs +++ b/src/Lucene.Net/Index/SegmentDocValues.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using Lucene.Net.Util; using System; @@ -112,7 +112,7 @@ internal void DecRef(IList dvProducersGens) { dvp.DecRef(); } - catch (Exception th) + catch (Exception th) when (th.IsThrowable()) { if (t != null) { diff --git a/src/Lucene.Net/Index/SegmentInfo.cs b/src/Lucene.Net/Index/SegmentInfo.cs index f310bb14b0..550cb1c704 100644 --- a/src/Lucene.Net/Index/SegmentInfo.cs +++ b/src/Lucene.Net/Index/SegmentInfo.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using System; using System.Collections.Generic; using Lucene.Net.Diagnostics; @@ -138,7 +138,7 @@ public Codec Codec set { if (Debugging.AssertsEnabled) Debugging.Assert(this.codec is null); - this.codec = value ?? throw new ArgumentNullException(nameof(value), "Codec must be non-null"); + this.codec = value ?? throw new ArgumentNullException(nameof(Codec), "Codec must be non-null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } } @@ -152,7 +152,7 @@ public int DocCount { if (this.docCount == -1) { - throw new InvalidOperationException("docCount isn't set yet"); + throw IllegalStateException.Create("docCount isn't set yet"); } return docCount; } @@ -160,7 +160,7 @@ public int DocCount { if (this.docCount != -1) { - throw new InvalidOperationException("docCount was already set"); + throw IllegalStateException.Create("docCount was already set"); } this.docCount = value; } @@ -172,7 +172,7 @@ public ISet GetFiles() { if (setFiles == null) { - throw new InvalidOperationException("files were not computed yet"); + throw IllegalStateException.Create("files were not computed yet"); } return setFiles.AsReadOnly(); } diff --git a/src/Lucene.Net/Index/SegmentInfos.cs b/src/Lucene.Net/Index/SegmentInfos.cs index 90cf8a08b1..48fe143101 100644 --- a/src/Lucene.Net/Index/SegmentInfos.cs +++ b/src/Lucene.Net/Index/SegmentInfos.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using JCG = J2N.Collections.Generic; @@ -218,7 +219,7 @@ public static long GetLastCommitGeneration(Directory directory) { return GetLastCommitGeneration(directory.ListAll()); } - catch (DirectoryNotFoundException) + catch (Exception nsde) when (nsde.IsNoSuchDirectoryException()) { return -1; } @@ -301,7 +302,7 @@ public static void WriteSegmentsGen(Directory dir, long generation) dir.Sync(new JCG.HashSet { IndexFileNames.SEGMENTS_GEN }); } } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // It's OK if we fail to write this file since it's // used only as one of the retry fallbacks. @@ -309,7 +310,7 @@ public static void WriteSegmentsGen(Directory dir, long generation) { dir.DeleteFile(IndexFileNames.SEGMENTS_GEN); } - catch (Exception) + catch (Exception t2) when (t2.IsThrowable()) { // Ignore; this file is only used in a retry // fallback on init. @@ -529,7 +530,7 @@ private void Write(Directory directory) int delCount = siPerCommit.DelCount; if (delCount < 0 || delCount > si.DocCount) { - throw new InvalidOperationException("cannot write segment: invalid docCount segment=" + si.Name + " docCount=" + si.DocCount + " delCount=" + delCount); + throw IllegalStateException.Create("cannot write segment: invalid docCount segment=" + si.Name + " docCount=" + si.DocCount + " delCount=" + delCount); } segnOutput.WriteInt32(delCount); segnOutput.WriteInt64(siPerCommit.FieldInfosGen); @@ -595,7 +596,7 @@ private void Write(Directory directory) { directory.DeleteFile(fileName); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // Suppress so we keep throwing the original exception } @@ -607,7 +608,7 @@ private void Write(Directory directory) // the index: directory.DeleteFile(segmentsFileName); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // Suppress so we keep throwing the original exception } @@ -628,7 +629,7 @@ private static bool SegmentWasUpgraded(Directory directory, SegmentInfo si) return true; } } - catch (IOException) + catch (Exception ioe) when (ioe.IsIOException()) { // Ignore: if something is wrong w/ the marker file, // we will just upgrade again @@ -659,7 +660,7 @@ public static string Write3xInfo(Directory dir, SegmentInfo si, IOContext contex // so it had better be a 3.x segment or you will get very confusing errors later. if ((si.Codec is Lucene3xCodec) == false) { - throw new InvalidOperationException("cannot write 3x SegmentInfo unless codec is Lucene3x (got: " + si.Codec + ")"); + throw IllegalStateException.Create("cannot write 3x SegmentInfo unless codec is Lucene3x (got: " + si.Codec + ")"); } CodecUtil.WriteHeader(output, Lucene3xSegmentInfoFormat.UPGRADED_SI_CODEC_NAME, Lucene3xSegmentInfoFormat.UPGRADED_SI_VERSION_CURRENT); @@ -686,7 +687,7 @@ public static string Write3xInfo(Directory dir, SegmentInfo si, IOContext contex { si.Dir.DeleteFile(fileName); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { // Suppress so we keep throwing the original exception } @@ -827,7 +828,7 @@ public virtual object Run(IndexCommit commit) long lastGen = -1; long gen = 0; int genLookaheadCount = 0; - IOException exc = null; + Exception exc = null; // LUCENENET: No need to cast to IOExcpetion int retryCount = 0; bool useFirstMethod = true; @@ -882,7 +883,7 @@ public virtual object Run(IndexCommit commit) { genInput = directory.OpenChecksumInput(IndexFileNames.SEGMENTS_GEN, IOContext.READ_ONCE); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { if (infoStream != null) { @@ -924,7 +925,7 @@ public virtual object Run(IndexCommit commit) throw new IndexFormatTooNewException(genInput, version, FORMAT_SEGMENTS_GEN_START, FORMAT_SEGMENTS_GEN_CURRENT); } } - catch (IOException err2) + catch (Exception err2) when (err2.IsIOException()) { // rethrow any format exception if (err2 is CorruptIndexException) @@ -978,7 +979,7 @@ public virtual object Run(IndexCommit commit) else { // All attempts have failed -- throw first exc: - throw exc; + ExceptionDispatchInfo.Capture(exc).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } } else if (lastGen == gen) @@ -1007,7 +1008,7 @@ public virtual object Run(IndexCommit commit) } return v; } - catch (IOException err) + catch (Exception err) when (err.IsIOException()) { // Save the original root cause: if (exc == null) @@ -1036,7 +1037,7 @@ public virtual object Run(IndexCommit commit) directory.OpenInput(prevSegmentFileName, IOContext.DEFAULT).Dispose(); prevExists = true; } - catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception ioe) when (ioe.IsIOException()) { prevExists = false; } @@ -1056,7 +1057,7 @@ public virtual object Run(IndexCommit commit) } return v; } - catch (IOException err2) + catch (Exception err2) when (err2.IsIOException()) { if (infoStream != null) { @@ -1119,7 +1120,7 @@ internal void PrepareCommit(Directory dir) { if (pendingSegnOutput != null) { - throw new InvalidOperationException("prepareCommit was already called"); + throw IllegalStateException.Create("prepareCommit was already called"); } Write(dir); } @@ -1161,7 +1162,7 @@ internal void FinishCommit(Directory dir) { if (pendingSegnOutput == null) { - throw new InvalidOperationException("prepareCommit was not called"); + throw IllegalStateException.Create("prepareCommit was not called"); } bool success = false; try diff --git a/src/Lucene.Net/Index/SegmentMerger.cs b/src/Lucene.Net/Index/SegmentMerger.cs index 34d617ec1b..96a41a4b37 100644 --- a/src/Lucene.Net/Index/SegmentMerger.cs +++ b/src/Lucene.Net/Index/SegmentMerger.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; @@ -89,7 +89,7 @@ internal MergeState Merge() { if (!ShouldMerge) { - throw new InvalidOperationException("Merge would result in 0 document segment"); + throw IllegalStateException.Create("Merge would result in 0 document segment"); } // NOTE: it's important to add calls to // checkAbort.work(...) if you make any changes to this @@ -251,7 +251,7 @@ private void MergeDocValues(SegmentWriteState segmentWriteState) } else { - throw new InvalidOperationException("type=" + type); + throw AssertionError.Create("type=" + type); } } } diff --git a/src/Lucene.Net/Index/SnapshotDeletionPolicy.cs b/src/Lucene.Net/Index/SnapshotDeletionPolicy.cs index 1ef2218f30..44c92e9dde 100644 --- a/src/Lucene.Net/Index/SnapshotDeletionPolicy.cs +++ b/src/Lucene.Net/Index/SnapshotDeletionPolicy.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; @@ -122,7 +122,7 @@ protected internal virtual void ReleaseGen(long gen) { if (!initCalled) { - throw new InvalidOperationException("this instance is not being used by IndexWriter; be sure to use the instance returned from writer.getConfig().getIndexDeletionPolicy()"); + throw IllegalStateException.Create("this instance is not being used by IndexWriter; be sure to use the instance returned from writer.Config.IndexDeletionPolicy"); } int? refCount = m_refCounts[gen]; if (refCount == null) @@ -186,12 +186,12 @@ public virtual IndexCommit Snapshot() { if (!initCalled) { - throw new InvalidOperationException("this instance is not being used by IndexWriter; be sure to use the instance returned from writer.getConfig().getIndexDeletionPolicy()"); + throw IllegalStateException.Create("this instance is not being used by IndexWriter; be sure to use the instance returned from writer.Config.IndexDeletionPolicy"); } if (m_lastCommit == null) { // No commit yet, eg this is a new IndexWriter: - throw new InvalidOperationException("No index commit to snapshot"); + throw IllegalStateException.Create("No index commit to snapshot"); } IncRef(m_lastCommit); diff --git a/src/Lucene.Net/Index/SortedDocValuesTermsEnum.cs b/src/Lucene.Net/Index/SortedDocValuesTermsEnum.cs index 157673aff0..8b7e8dbf7e 100644 --- a/src/Lucene.Net/Index/SortedDocValuesTermsEnum.cs +++ b/src/Lucene.Net/Index/SortedDocValuesTermsEnum.cs @@ -122,18 +122,18 @@ public override BytesRef Next() public override long Ord => currentOrd; - public override int DocFreq => throw new NotSupportedException(); + public override int DocFreq => throw UnsupportedOperationException.Create(); public override long TotalTermFreq => -1; public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override IComparer Comparer => BytesRef.UTF8SortedAsUnicodeComparer; diff --git a/src/Lucene.Net/Index/SortedDocValuesWriter.cs b/src/Lucene.Net/Index/SortedDocValuesWriter.cs index 57c4cbd016..2fd345bd04 100644 --- a/src/Lucene.Net/Index/SortedDocValuesWriter.cs +++ b/src/Lucene.Net/Index/SortedDocValuesWriter.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Codecs; +using Lucene.Net.Codecs; using Lucene.Net.Diagnostics; using Lucene.Net.Util; using Lucene.Net.Util.Packed; @@ -55,9 +55,9 @@ public virtual void AddValue(int docID, BytesRef value) { throw new ArgumentException("DocValuesField \"" + fieldInfo.Name + "\" appears more than once in this document (only one value is allowed per field)"); } - if (value == null) + if (value is null) { - throw new ArgumentException("field \"" + fieldInfo.Name + "\": null value not allowed"); + throw new ArgumentNullException("field \"" + fieldInfo.Name + "\": null value not allowed"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } if (value.Length > (ByteBlockPool.BYTE_BLOCK_SIZE - 2)) { diff --git a/src/Lucene.Net/Index/SortedSetDocValuesTermsEnum.cs b/src/Lucene.Net/Index/SortedSetDocValuesTermsEnum.cs index 3aec7036fd..1f51b6e940 100644 --- a/src/Lucene.Net/Index/SortedSetDocValuesTermsEnum.cs +++ b/src/Lucene.Net/Index/SortedSetDocValuesTermsEnum.cs @@ -122,18 +122,18 @@ public override BytesRef Next() public override long Ord => currentOrd; - public override int DocFreq => throw new NotSupportedException(); + public override int DocFreq => throw UnsupportedOperationException.Create(); public override long TotalTermFreq => -1; public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override IComparer Comparer => BytesRef.UTF8SortedAsUnicodeComparer; diff --git a/src/Lucene.Net/Index/SortedSetDocValuesWriter.cs b/src/Lucene.Net/Index/SortedSetDocValuesWriter.cs index fc2484eeaa..3cabc9a2c4 100644 --- a/src/Lucene.Net/Index/SortedSetDocValuesWriter.cs +++ b/src/Lucene.Net/Index/SortedSetDocValuesWriter.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -64,9 +64,9 @@ public SortedSetDocValuesWriter(FieldInfo fieldInfo, Counter iwBytesUsed) public virtual void AddValue(int docID, BytesRef value) { - if (value == null) + if (value is null) { - throw new ArgumentException("field \"" + fieldInfo.Name + "\": null value not allowed"); + throw new ArgumentNullException("field \"" + fieldInfo.Name + "\": null value not allowed"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } if (value.Length > (ByteBlockPool.BYTE_BLOCK_SIZE - 2)) { diff --git a/src/Lucene.Net/Index/StandardDirectoryReader.cs b/src/Lucene.Net/Index/StandardDirectoryReader.cs index 33aac6b5c7..6a7dd210ea 100644 --- a/src/Lucene.Net/Index/StandardDirectoryReader.cs +++ b/src/Lucene.Net/Index/StandardDirectoryReader.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; @@ -68,24 +68,21 @@ protected internal override object DoBody(string segmentFileName) var sis = new SegmentInfos(); sis.Read(directory, segmentFileName); var readers = new SegmentReader[sis.Count]; + // LUCENENET: Ported over changes from 4.8.1 to this method for (int i = sis.Count - 1; i >= 0; i--) { - IOException prior = null; + //IOException prior = null; // LUCENENET: Not used bool success = false; try { readers[i] = new SegmentReader(sis.Info(i), termInfosIndexDivisor, IOContext.READ); success = true; } - catch (IOException ex) - { - prior = ex; - } finally { if (!success) { - IOUtils.DisposeWhileHandlingException(prior, readers); + IOUtils.DisposeWhileHandlingException(readers); } } } @@ -156,7 +153,7 @@ internal static DirectoryReader Open(IndexWriter writer, SegmentInfos infos, boo { r.DecRef(); } - catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception th) when (th.IsThrowable()) { // ignore any exception that is thrown here to not mask any original // exception. @@ -250,7 +247,7 @@ private static DirectoryReader Open(Directory directory, SegmentInfos infos, ILi } success = true; } - catch (Exception ex) + catch (Exception ex) when (ex.IsThrowable()) { prior = ex; } @@ -277,7 +274,7 @@ private static DirectoryReader Open(Directory directory, SegmentInfos infos, ILi newReaders[i].DecRef(); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (prior == null) { @@ -468,7 +465,7 @@ protected internal override void DoClose() { r.DecRef(); } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { if (firstExc == null) { @@ -483,7 +480,7 @@ protected internal override void DoClose() { writer.DecRefDeleter(segmentInfos); } - catch (ObjectDisposedException) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception ex) when (ex.IsAlreadyClosedException()) { // this is OK, it just means our original writer was // closed before we were, and this may leave some @@ -546,7 +543,7 @@ public override string ToString() public override void Delete() { - throw new NotSupportedException("this IndexCommit does not support deletions"); + throw UnsupportedOperationException.Create("this IndexCommit does not support deletions"); } } } diff --git a/src/Lucene.Net/Index/Terms.cs b/src/Lucene.Net/Index/Terms.cs index b391e482c1..5fe6cf0108 100644 --- a/src/Lucene.Net/Index/Terms.cs +++ b/src/Lucene.Net/Index/Terms.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -85,7 +85,7 @@ public virtual TermsEnum Intersect(CompiledAutomaton compiled, BytesRef startTer // at the start if (compiled.Type != CompiledAutomaton.AUTOMATON_TYPE.NORMAL) { - throw new ArgumentException("please use CompiledAutomaton.getTermsEnum instead"); + throw new ArgumentException("please use CompiledAutomaton.TermsEnum instead"); } if (startTerm == null) { diff --git a/src/Lucene.Net/Index/TermsEnum.cs b/src/Lucene.Net/Index/TermsEnum.cs index 25a9a2810f..c185b93e56 100644 --- a/src/Lucene.Net/Index/TermsEnum.cs +++ b/src/Lucene.Net/Index/TermsEnum.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Util; +using Lucene.Net.Util; using System; using System.Collections.Generic; using System.ComponentModel; @@ -275,7 +275,7 @@ private class TermStateAnonymousClass : TermState { public override void CopyFrom(TermState other) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } @@ -300,24 +300,24 @@ public override void SeekExact(long ord) { } - public override BytesRef Term => throw new InvalidOperationException("this method should never be called"); + public override BytesRef Term => throw IllegalStateException.Create("this method should never be called"); public override IComparer Comparer => null; - public override int DocFreq => throw new InvalidOperationException("this method should never be called"); + public override int DocFreq => throw IllegalStateException.Create("this method should never be called"); - public override long TotalTermFreq => throw new InvalidOperationException("this method should never be called"); + public override long TotalTermFreq => throw IllegalStateException.Create("this method should never be called"); - public override long Ord => throw new InvalidOperationException("this method should never be called"); + public override long Ord => throw IllegalStateException.Create("this method should never be called"); public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { - throw new InvalidOperationException("this method should never be called"); + throw IllegalStateException.Create("this method should never be called"); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { - throw new InvalidOperationException("this method should never be called"); + throw IllegalStateException.Create("this method should never be called"); } // LUCENENET specific @@ -345,12 +345,12 @@ public override BytesRef Next() public override TermState GetTermState() { - throw new InvalidOperationException("this method should never be called"); + throw IllegalStateException.Create("this method should never be called"); } public override void SeekExact(BytesRef term, TermState state) { - throw new InvalidOperationException("this method should never be called"); + throw IllegalStateException.Create("this method should never be called"); } } } diff --git a/src/Lucene.Net/Index/TieredMergePolicy.cs b/src/Lucene.Net/Index/TieredMergePolicy.cs index 1524d9fc38..2d2ba07edf 100644 --- a/src/Lucene.Net/Index/TieredMergePolicy.cs +++ b/src/Lucene.Net/Index/TieredMergePolicy.cs @@ -1,4 +1,4 @@ -using J2N.Text; +using J2N.Text; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -111,7 +111,7 @@ public virtual int MaxMergeAtOnce { if (value < 2) { - throw new ArgumentException("maxMergeAtOnce must be > 1 (got " + value + ")"); + throw new ArgumentOutOfRangeException(nameof(MaxMergeAtOnce), "maxMergeAtOnce must be > 1 (got " + value + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } maxMergeAtOnce = value; } @@ -132,7 +132,7 @@ public virtual int MaxMergeAtOnceExplicit { if (value < 2) { - throw new ArgumentException("maxMergeAtOnceExplicit must be > 1 (got " + value + ")"); + throw new ArgumentOutOfRangeException(nameof(MaxMergeAtOnceExplicit), "maxMergeAtOnceExplicit must be > 1 (got " + value + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } maxMergeAtOnceExplicit = value; } @@ -152,7 +152,7 @@ public virtual double MaxMergedSegmentMB { if (value < 0.0) { - throw new ArgumentException("maxMergedSegmentMB must be >=0 (got " + value.ToString("0.0") + ")"); + throw new ArgumentOutOfRangeException(nameof(MaxMergedSegmentMB), "maxMergedSegmentMB must be >=0 (got " + value.ToString("0.0") + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } value *= 1024 * 1024; maxMergedSegmentBytes = (value > long.MaxValue) ? long.MaxValue : (long)value; @@ -175,7 +175,7 @@ public virtual double ReclaimDeletesWeight { if (value < 0.0) { - throw new ArgumentException("reclaimDeletesWeight must be >= 0.0 (got " + value.ToString("0.0") + ")"); + throw new ArgumentOutOfRangeException(nameof(ReclaimDeletesWeight), "reclaimDeletesWeight must be >= 0.0 (got " + value.ToString("0.0") + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } reclaimDeletesWeight = value; } @@ -195,7 +195,7 @@ public virtual double FloorSegmentMB { if (value <= 0.0) { - throw new ArgumentException("floorSegmentMB must be >= 0.0 (got " + value.ToString("0.0") + ")"); + throw new ArgumentOutOfRangeException(nameof(FloorSegmentMB), "floorSegmentMB must be >= 0.0 (got " + value.ToString("0.0") + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } value *= 1024 * 1024; floorSegmentBytes = (value > long.MaxValue) ? long.MaxValue : (long)value; @@ -214,7 +214,7 @@ public virtual double ForceMergeDeletesPctAllowed { if (value < 0.0 || value > 100.0) { - throw new ArgumentException("forceMergeDeletesPctAllowed must be between 0.0 and 100.0 inclusive (got " + value.ToString("0.0") + ")"); + throw new ArgumentOutOfRangeException(nameof(ForceMergeDeletesPctAllowed), "forceMergeDeletesPctAllowed must be between 0.0 and 100.0 inclusive (got " + value.ToString("0.0") + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } forceMergeDeletesPctAllowed = value; } @@ -237,7 +237,7 @@ public virtual double SegmentsPerTier { if (value < 2.0) { - throw new ArgumentException("segmentsPerTier must be >= 2.0 (got " + value.ToString("0.0") + ")"); + throw new ArgumentOutOfRangeException(nameof(SegmentsPerTier), "segmentsPerTier must be >= 2.0 (got " + value.ToString("0.0") + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } segsPerTier = value; } @@ -271,9 +271,9 @@ public virtual int Compare(SegmentCommitInfo o1, SegmentCommitInfo o2) return o1.Info.Name.CompareToOrdinal(o2.Info.Name); } } - 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/Index/TwoPhaseCommitTool.cs b/src/Lucene.Net/Index/TwoPhaseCommitTool.cs index 25f0fb3971..0289c15bae 100644 --- a/src/Lucene.Net/Index/TwoPhaseCommitTool.cs +++ b/src/Lucene.Net/Index/TwoPhaseCommitTool.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; #if FEATURE_SERIALIZABLE_EXCEPTIONS using System.Runtime.Serialization; @@ -56,13 +56,13 @@ public PrepareCommitFailException(Exception cause, ITwoPhaseCommit obj) { } -#if FEATURE_SERIALIZABLE_EXCEPTIONS - // For testing purposes - public PrepareCommitFailException(string message) + // LUCENENET: For testing purposes + internal PrepareCommitFailException(string message) : base(message) { } +#if FEATURE_SERIALIZABLE_EXCEPTIONS /// /// Initializes a new instance of this class with serialized data. /// @@ -93,13 +93,13 @@ public CommitFailException(Exception cause, ITwoPhaseCommit obj) { } -#if FEATURE_SERIALIZABLE_EXCEPTIONS - // For testing purposes - public CommitFailException(string message) + // LUCENENET: For testing purposes + internal CommitFailException(string message) : base(message) { } +#if FEATURE_SERIALIZABLE_EXCEPTIONS /// /// Initializes a new instance of this class with serialized data. /// @@ -126,7 +126,7 @@ private static void Rollback(params ITwoPhaseCommit[] objects) { tpc.Rollback(); } - catch (Exception) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception t) when (t.IsThrowable()) { // ignore } @@ -169,7 +169,7 @@ public static void Execute(params ITwoPhaseCommit[] objects) } } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { // first object that fails results in rollback all of them and // throwing an exception. @@ -189,7 +189,7 @@ public static void Execute(params ITwoPhaseCommit[] objects) } } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { // first object that fails results in rollback all of them and // throwing an exception. diff --git a/src/Lucene.Net/Index/TwoStoredFieldsConsumers.cs b/src/Lucene.Net/Index/TwoStoredFieldsConsumers.cs index d7f74f4abb..ab53128592 100644 --- a/src/Lucene.Net/Index/TwoStoredFieldsConsumers.cs +++ b/src/Lucene.Net/Index/TwoStoredFieldsConsumers.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.CompilerServices; namespace Lucene.Net.Index @@ -53,14 +53,14 @@ public override void Abort() // LUCENENET NOTE: original was internal, but other { first.Abort(); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { } try { second.Abort(); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { } } diff --git a/src/Lucene.Net/Lucene.Net.csproj b/src/Lucene.Net/Lucene.Net.csproj index 551bd53ba1..0bb541a19f 100644 --- a/src/Lucene.Net/Lucene.Net.csproj +++ b/src/Lucene.Net/Lucene.Net.csproj @@ -101,10 +101,16 @@ + + + + + + @@ -116,6 +122,7 @@ + diff --git a/src/Lucene.Net/Search/BitsFilteredDocIdSet.cs b/src/Lucene.Net/Search/BitsFilteredDocIdSet.cs index 1b689edc0c..73f7b7b143 100644 --- a/src/Lucene.Net/Search/BitsFilteredDocIdSet.cs +++ b/src/Lucene.Net/Search/BitsFilteredDocIdSet.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Lucene.Net.Search { @@ -50,7 +50,7 @@ public static DocIdSet Wrap(DocIdSet set, IBits acceptDocs) public BitsFilteredDocIdSet(DocIdSet innerSet, IBits acceptDocs) : base(innerSet) { - this.acceptDocs = acceptDocs ?? throw new ArgumentNullException(nameof(acceptDocs), "acceptDocs can not be null"); + this.acceptDocs = acceptDocs ?? throw new ArgumentNullException(nameof(acceptDocs), "acceptDocs can not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } protected override bool Match(int docid) diff --git a/src/Lucene.Net/Search/BooleanClause.cs b/src/Lucene.Net/Search/BooleanClause.cs index fff6043731..621f1ca4ae 100644 --- a/src/Lucene.Net/Search/BooleanClause.cs +++ b/src/Lucene.Net/Search/BooleanClause.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Lucene.Net.Search { @@ -43,7 +43,7 @@ public static string ToString(Occur occur) return "-"; default: - throw new Exception("Invalid Occur value"); + throw new ArgumentOutOfRangeException("Invalid Occur value"); // LUCENENET specific } } diff --git a/src/Lucene.Net/Search/BooleanQuery.cs b/src/Lucene.Net/Search/BooleanQuery.cs index 59f225b062..29cc92ae62 100644 --- a/src/Lucene.Net/Search/BooleanQuery.cs +++ b/src/Lucene.Net/Search/BooleanQuery.cs @@ -1,4 +1,4 @@ -using J2N; +using J2N; using J2N.Collections.Generic.Extensions; using System; using System.Collections; @@ -82,7 +82,8 @@ public class BooleanQuery : Query, IEnumerable #if FEATURE_SERIALIZABLE_EXCEPTIONS [Serializable] #endif - public class TooManyClausesException : Exception // LUCENENET specific - added Exception suffix + // LUCENENET specific: Added IRuntimeException for identification of the Java superclass in .NET + public class TooManyClausesException : Exception, IRuntimeException // LUCENENET specific - added Exception suffix { public TooManyClausesException() : base("maxClauseCount is set to " + maxClauseCount) @@ -113,7 +114,7 @@ public static int MaxClauseCount { if (value < 1) { - throw new ArgumentException("maxClauseCount must be >= 1"); + throw new ArgumentOutOfRangeException(nameof(MaxClauseCount), "maxClauseCount must be >= 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } BooleanQuery.maxClauseCount = value; } diff --git a/src/Lucene.Net/Search/BooleanScorer2.cs b/src/Lucene.Net/Search/BooleanScorer2.cs index 0414f54fde..f33413b06f 100644 --- a/src/Lucene.Net/Search/BooleanScorer2.cs +++ b/src/Lucene.Net/Search/BooleanScorer2.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using System; using System.Collections.Generic; @@ -95,7 +95,7 @@ public BooleanScorer2(BooleanWeight weight, bool disableCoord, int minNrShouldMa { if (minNrShouldMatch < 0) { - throw new ArgumentException("Minimum number of optional scorers should not be negative"); + throw new ArgumentOutOfRangeException(nameof(minNrShouldMatch), "Minimum number of optional scorers should not be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.minNrShouldMatch = minNrShouldMatch; diff --git a/src/Lucene.Net/Search/CachingCollector.cs b/src/Lucene.Net/Search/CachingCollector.cs index cefff44bca..7cbdc7a1ef 100644 --- a/src/Lucene.Net/Search/CachingCollector.cs +++ b/src/Lucene.Net/Search/CachingCollector.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -93,16 +93,16 @@ public override float GetScore() public override int Advance(int target) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override int DocID => doc; - public override int Freq => throw new NotSupportedException(); + public override int Freq => throw UnsupportedOperationException.Create(); public override int NextDoc() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override long GetCost() @@ -510,12 +510,14 @@ internal virtual void ReplayInit(ICollector other) { if (!IsCached) { - throw new InvalidOperationException("cannot replay: cache was cleared because too much RAM was required"); + throw IllegalStateException.Create("cannot replay: cache was cleared because too much RAM was required"); } if (!other.AcceptsDocsOutOfOrder && this.m_other.AcceptsDocsOutOfOrder) { - throw new ArgumentException("cannot replay: given collector does not support " + "out-of-order collection, while the wrapped collector does. " + "Therefore cached documents may be out-of-order."); + throw new ArgumentException("cannot replay: given collector does not support " + + "out-of-order collection, while the wrapped collector does. " + + "Therefore cached documents may be out-of-order."); } //System.out.println("CC: replay totHits=" + (upto + base)); diff --git a/src/Lucene.Net/Search/CollectionTerminatedException.cs b/src/Lucene.Net/Search/CollectionTerminatedException.cs index e2e202346a..1acd67052f 100644 --- a/src/Lucene.Net/Search/CollectionTerminatedException.cs +++ b/src/Lucene.Net/Search/CollectionTerminatedException.cs @@ -1,4 +1,4 @@ -using System; +using System; #if FEATURE_SERIALIZABLE_EXCEPTIONS using System.Runtime.Serialization; #endif @@ -35,7 +35,7 @@ namespace Lucene.Net.Search #if FEATURE_SERIALIZABLE_EXCEPTIONS [Serializable] #endif - public sealed class CollectionTerminatedException : Exception + public sealed class CollectionTerminatedException : Exception, IRuntimeException // LUCENENET specific: Added IRuntimeException for identification of the Java superclass in .NET { /// /// Sole constructor. diff --git a/src/Lucene.Net/Search/ConstantScoreQuery.cs b/src/Lucene.Net/Search/ConstantScoreQuery.cs index 12b8266f82..4bcb85783f 100644 --- a/src/Lucene.Net/Search/ConstantScoreQuery.cs +++ b/src/Lucene.Net/Search/ConstantScoreQuery.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using System; using System.Collections.Generic; using Lucene.Net.Diagnostics; @@ -43,10 +43,12 @@ public class ConstantScoreQuery : Query /// Strips off scores from the passed in . The hits will get a constant score /// dependent on the boost factor of this query. /// + /// if is null. public ConstantScoreQuery(Query query) { + // LUCENENET specific: Changed guard clause to throw ArgumentNullException instead of NullPointerException this.m_filter = null; - this.m_query = query ?? throw new NullReferenceException("Query may not be null"); + this.m_query = query ?? throw new ArgumentNullException(nameof(query), "Query may not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// @@ -56,9 +58,11 @@ public ConstantScoreQuery(Query query) /// new ConstantScoreQuery(new QueryWrapperFilter(query)), instead /// use ! /// + /// if is null. public ConstantScoreQuery(Filter filter) { - this.m_filter = filter ?? throw new NullReferenceException("Filter may not be null"); + // LUCENENET specific: Changed guard clause to throw ArgumentNullException instead of NullPointerException + this.m_filter = filter ?? throw new ArgumentNullException(nameof(filter), "Filter may not be null"); this.m_query = null; } diff --git a/src/Lucene.Net/Search/ControlledRealTimeReopenThread.cs b/src/Lucene.Net/Search/ControlledRealTimeReopenThread.cs index 690846f393..ec5c585157 100644 --- a/src/Lucene.Net/Search/ControlledRealTimeReopenThread.cs +++ b/src/Lucene.Net/Search/ControlledRealTimeReopenThread.cs @@ -243,7 +243,7 @@ public override void Run() { reopenCond.WaitOne(TimeSpan.FromMilliseconds(sleepNS / Time.MILLISECONDS_PER_NANOSECOND));//Convert NS to Ticks } - catch (ThreadInterruptedException) + catch (Exception ie) when (ie.IsInterruptedException()) { Thread.CurrentThread.Interrupt(); return; @@ -263,9 +263,9 @@ public override void Run() { manager.MaybeRefreshBlocking(); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception(ioe.ToString(), ioe); + throw RuntimeException.Create(ioe); } } // this will set the searchingGen so that all waiting threads will exit diff --git a/src/Lucene.Net/Search/FakeScorer.cs b/src/Lucene.Net/Search/FakeScorer.cs index 637551d85f..477ba4e2b6 100644 --- a/src/Lucene.Net/Search/FakeScorer.cs +++ b/src/Lucene.Net/Search/FakeScorer.cs @@ -37,7 +37,7 @@ 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; @@ -46,7 +46,7 @@ public override int Advance(int target) 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/Search/FieldCache.cs b/src/Lucene.Net/Search/FieldCache.cs index 365718c338..daf1447c67 100644 --- a/src/Lucene.Net/Search/FieldCache.cs +++ b/src/Lucene.Net/Search/FieldCache.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; @@ -378,7 +378,7 @@ public class Bytes // LUCENENET specific - removed abstract so we can pass a del /// delegate method. /// /// A that implements the method body. - public Bytes(Func get) + public Bytes(Func get) // LUCENENET specific - Added constructor overload to simulate anonymous classes { this.get = get ?? throw new ArgumentNullException(nameof(get)); this.hasGet = true; @@ -415,7 +415,7 @@ public class Int16s // LUCENENET specific - removed abstract so we can pass a de /// delegate method. /// /// A that implements the method body. - public Int16s(Func get) + public Int16s(Func get) // LUCENENET specific - Added constructor overload to simulate anonymous classes { this.get = get ?? throw new ArgumentNullException(nameof(get)); this.hasGet = true; @@ -452,7 +452,7 @@ public class Int32s // LUCENENET specific - removed abstract so we can pass a de /// delegate method. /// /// A that implements the method body. - public Int32s(Func get) + public Int32s(Func get) // LUCENENET specific - Added constructor overload for to simulate anonymous classes { this.get = get ?? throw new ArgumentNullException(nameof(get)); this.hasGet = true; @@ -489,7 +489,7 @@ public class Int64s // LUCENENET specific - removed abstract so we can pass a de /// delegate method. /// /// A that implements the method body. - public Int64s(Func get) + public Int64s(Func get) // LUCENENET: Added constructor overload to simulate anonymous classes { this.get = get ?? throw new ArgumentNullException(nameof(get)); this.hasGet = true; @@ -526,7 +526,7 @@ public class Singles // LUCENENET specific - removed abstract so we can pass a d /// delegate method. /// /// A that implements the method body. - public Singles(Func get) + public Singles(Func get) // LUCENENET: Added constructor overload to simulate anonymous classes { this.get = get ?? throw new ArgumentNullException(nameof(get)); this.hasGet = true; @@ -561,7 +561,7 @@ public class Doubles // LUCENENET specific - removed abstract so we can pass a d /// delegate method. /// /// A that implements the method body. - public Doubles(Func get) + public Doubles(Func get) // LUCENENET: Added constructor overload to simulate anonymous classes { this.get = get ?? throw new ArgumentNullException(nameof(get)); this.hasGet = true; diff --git a/src/Lucene.Net/Search/FieldCacheImpl.cs b/src/Lucene.Net/Search/FieldCacheImpl.cs index 681f097c15..c874c196c6 100644 --- a/src/Lucene.Net/Search/FieldCacheImpl.cs +++ b/src/Lucene.Net/Search/FieldCacheImpl.cs @@ -597,7 +597,7 @@ public virtual FieldCache.Bytes GetBytes(AtomicReader reader, string field, Fiel } else if (info.HasDocValues) { - throw new InvalidOperationException("Type mismatch: " + field + " was indexed as " + info.DocValuesType); + throw IllegalStateException.Create("Type mismatch: " + field + " was indexed as " + info.DocValuesType); } else if (!info.IsIndexed) { @@ -770,7 +770,7 @@ public virtual FieldCache.Int16s GetInt16s(AtomicReader reader, string field, Fi } else if (info.HasDocValues) { - throw new InvalidOperationException("Type mismatch: " + field + " was indexed as " + info.DocValuesType); + throw IllegalStateException.Create("Type mismatch: " + field + " was indexed as " + info.DocValuesType); } else if (!info.IsIndexed) { @@ -942,7 +942,7 @@ public virtual FieldCache.Int32s GetInt32s(AtomicReader reader, string field, Fi } else if (info.HasDocValues) { - throw new InvalidOperationException("Type mismatch: " + field + " was indexed as " + info.DocValuesType); + throw IllegalStateException.Create("Type mismatch: " + field + " was indexed as " + info.DocValuesType); } else if (!info.IsIndexed) { @@ -1043,7 +1043,7 @@ protected override FieldCache.Int32s CreateValue(AtomicReader reader, CacheKey=0 (got ord=" + ord + ")"); + throw new ArgumentOutOfRangeException(nameof(ord), "ord must be >=0 (got ord=" + ord + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } bytes.Fill(ret, termOrdToBytesOffset.Get(ord)); } @@ -1771,7 +1771,7 @@ public virtual SortedDocValues GetTermsIndex(AtomicReader reader, string field, { // we don't try to build a sorted instance from numeric/binary doc // values because dedup can be very costly - throw new InvalidOperationException("Type mismatch: " + field + " was indexed as " + info.DocValuesType); + throw IllegalStateException.Create("Type mismatch: " + field + " was indexed as " + info.DocValuesType); } else if (!info.IsIndexed) { @@ -1937,7 +1937,7 @@ public virtual BinaryDocValues GetTerms(AtomicReader reader, string field, bool } else if (info.HasDocValues) { - throw new InvalidOperationException("Type mismatch: " + field + " was indexed as " + info.DocValuesType); + throw IllegalStateException.Create("Type mismatch: " + field + " was indexed as " + info.DocValuesType); } else if (!info.IsIndexed) { @@ -2087,7 +2087,7 @@ public virtual SortedSetDocValues GetDocTermOrds(AtomicReader reader, string fie } else if (info.HasDocValues) { - throw new InvalidOperationException("Type mismatch: " + field + " was indexed as " + info.DocValuesType); + throw IllegalStateException.Create("Type mismatch: " + field + " was indexed as " + info.DocValuesType); } else if (!info.IsIndexed) { diff --git a/src/Lucene.Net/Search/FieldComparator.cs b/src/Lucene.Net/Search/FieldComparator.cs index 140e3042b7..a670812805 100644 --- a/src/Lucene.Net/Search/FieldComparator.cs +++ b/src/Lucene.Net/Search/FieldComparator.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.IO; @@ -1482,9 +1482,9 @@ public override void SetBottom(int slot) public override void SetTopValue(object value) { - if (value == null) + if (value is null) { - throw new ArgumentException("value cannot be null"); + throw new ArgumentNullException(nameof(value), "value cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } topValue = (BytesRef)value; } diff --git a/src/Lucene.Net/Search/FilteredDocIdSetIterator.cs b/src/Lucene.Net/Search/FilteredDocIdSetIterator.cs index 7723dd3acd..4e604b448b 100644 --- a/src/Lucene.Net/Search/FilteredDocIdSetIterator.cs +++ b/src/Lucene.Net/Search/FilteredDocIdSetIterator.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Lucene.Net.Search { @@ -35,7 +35,7 @@ public abstract class FilteredDocIdSetIterator : DocIdSetIterator /// Underlying . protected FilteredDocIdSetIterator(DocIdSetIterator innerIter) // LUCENENET: CA1012: Abstract types should not have constructors (marked protected) { - m_innerIter = innerIter ?? throw new ArgumentNullException(nameof(innerIter), "null iterator"); + m_innerIter = innerIter ?? throw new ArgumentNullException(nameof(innerIter), "null iterator"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) doc = -1; } diff --git a/src/Lucene.Net/Search/FilteredQuery.cs b/src/Lucene.Net/Search/FilteredQuery.cs index 3c9c8fe728..b7f1db6da3 100644 --- a/src/Lucene.Net/Search/FilteredQuery.cs +++ b/src/Lucene.Net/Search/FilteredQuery.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.IO; @@ -64,7 +64,8 @@ public FilteredQuery(Query query, Filter filter) /// public FilteredQuery(Query query, Filter filter, FilterStrategy strategy) { - // LUCENENET specific - rearranged order to take advantage of throw expressions + // LUCENENET specific - rearranged order to take advantage of throw expressions and + // changed from IllegalArgumentException to ArgumentNullException (.NET convention) this.query = query ?? throw new ArgumentNullException(nameof(query), "Query cannot be null."); this.filter = filter ?? throw new ArgumentNullException(nameof(filter), "filter can not be null"); this.strategy = strategy ?? throw new ArgumentNullException(nameof(strategy), "FilterStrategy can not be null"); diff --git a/src/Lucene.Net/Search/FuzzyQuery.cs b/src/Lucene.Net/Search/FuzzyQuery.cs index d9944ced46..5c70213841 100644 --- a/src/Lucene.Net/Search/FuzzyQuery.cs +++ b/src/Lucene.Net/Search/FuzzyQuery.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text; namespace Lucene.Net.Search @@ -86,15 +86,15 @@ public FuzzyQuery(Term term, int maxEdits, int prefixLength, int maxExpansions, { 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 (prefixLength < 0) { - throw new ArgumentException("prefixLength cannot be negative."); + throw new ArgumentOutOfRangeException(nameof(prefixLength), "prefixLength cannot be negative."); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (maxExpansions < 0) { - throw new ArgumentException("maxExpansions cannot be negative."); + throw new ArgumentOutOfRangeException(nameof(maxExpansions), "maxExpansions cannot be negative."); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.term = term; diff --git a/src/Lucene.Net/Search/FuzzyTermsEnum.cs b/src/Lucene.Net/Search/FuzzyTermsEnum.cs index 8f56d3eb60..c28eeeb98b 100644 --- a/src/Lucene.Net/Search/FuzzyTermsEnum.cs +++ b/src/Lucene.Net/Search/FuzzyTermsEnum.cs @@ -1,4 +1,4 @@ -using J2N; +using J2N; using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using Lucene.Net.Index; @@ -114,11 +114,11 @@ public FuzzyTermsEnum(Terms terms, AttributeSource atts, Term term, float minSim } if (minSimilarity < 0.0f) { - throw new ArgumentException("minimumSimilarity cannot be less than 0"); + throw new ArgumentOutOfRangeException(nameof(minSimilarity), "minimumSimilarity cannot be less than 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (prefixLength < 0) { - throw new ArgumentException("prefixLength cannot be less than 0"); + throw new ArgumentOutOfRangeException(nameof(prefixLength), "prefixLength cannot be less than 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.m_terms = terms; this.term = term; @@ -152,7 +152,7 @@ public FuzzyTermsEnum(Terms terms, AttributeSource atts, Term term, float minSim } if (transpositions && m_maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE) { - throw new NotSupportedException("with transpositions enabled, distances > " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE + " are not supported "); + throw UnsupportedOperationException.Create("with transpositions enabled, distances > " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE + " are not supported "); } this.transpositions = transpositions; this.m_scaleFactor = 1.0f / (1.0f - this.m_minSimilarity); diff --git a/src/Lucene.Net/Search/IndexSearcher.cs b/src/Lucene.Net/Search/IndexSearcher.cs index a0a02ff841..50e921322f 100644 --- a/src/Lucene.Net/Search/IndexSearcher.cs +++ b/src/Lucene.Net/Search/IndexSearcher.cs @@ -439,7 +439,7 @@ protected virtual TopDocs Search(Weight weight, ScoreDoc after, int nDocs) } if (after != null && after.Doc >= limit) { - throw new ArgumentException("after.doc exceeds the number of documents in the reader: after.doc=" + after.Doc + " limit=" + limit); + throw new ArgumentException("after.Doc exceeds the number of documents in the reader: after.Doc=" + after.Doc + " limit=" + limit); } nDocs = Math.Min(nDocs, limit); @@ -525,9 +525,9 @@ protected virtual TopFieldDocs Search(Weight weight, int nDocs, Sort sort, bool /// protected virtual TopFieldDocs Search(Weight weight, FieldDoc after, int nDocs, Sort sort, bool fillFields, bool doDocScores, bool doMaxScore) { - if (sort == null) + if (sort is null) { - throw new ArgumentNullException("Sort must not be null"); + throw new ArgumentNullException("Sort must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } int limit = reader.MaxDoc; @@ -863,7 +863,7 @@ public void Submit(ICallable task) public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public bool MoveNext() @@ -878,16 +878,14 @@ public bool MoveNext() return true; } - catch (ThreadInterruptedException /*e*/) + catch (Exception e) when (e.IsInterruptedException()) { - //throw new ThreadInterruptedException(e.ToString(), e); + // LUCENENET: Throwing as same type, no need to wrap here 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 e) { - // LUCENENET NOTE: We need to re-throw this as Exception to - // ensure it is not caught in the wrong place - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } finally { diff --git a/src/Lucene.Net/Search/MinShouldMatchSumScorer.cs b/src/Lucene.Net/Search/MinShouldMatchSumScorer.cs index 0bab089e4d..293965eee5 100644 --- a/src/Lucene.Net/Search/MinShouldMatchSumScorer.cs +++ b/src/Lucene.Net/Search/MinShouldMatchSumScorer.cs @@ -1,4 +1,4 @@ -using J2N; +using J2N; using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using System; @@ -89,11 +89,11 @@ public MinShouldMatchSumScorer(Weight weight, IList subScorers, int mini if (minimumNrMatchers <= 0) { - throw new ArgumentException("Minimum nr of matchers must be positive"); + throw new ArgumentOutOfRangeException(nameof(minimumNrMatchers), "Minimum nr of matchers must be positive"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (numScorers <= 1) { - throw new ArgumentException("There must be at least 2 subScorers"); + throw new ArgumentOutOfRangeException(nameof(numScorers), "There must be at least 2 subScorers"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.mm = minimumNrMatchers; diff --git a/src/Lucene.Net/Search/MultiPhraseQuery.cs b/src/Lucene.Net/Search/MultiPhraseQuery.cs index 78faddd6b9..37105ccf14 100644 --- a/src/Lucene.Net/Search/MultiPhraseQuery.cs +++ b/src/Lucene.Net/Search/MultiPhraseQuery.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Support; using System; @@ -85,7 +85,7 @@ public virtual int Slop set { if (value < 0) - throw new ArgumentException("slop value cannot be negative"); + throw new ArgumentOutOfRangeException(nameof(Slop), "slop value cannot be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) slop = value; } @@ -285,7 +285,7 @@ public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { // term does exist, but has no positions if (Debugging.AssertsEnabled) Debugging.Assert(termsEnum.Docs(liveDocs, null, DocsFlags.NONE) != null, "termstate found but no term exists in reader"); - throw new InvalidOperationException("field \"" + term.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + term.Text() + ")"); + throw IllegalStateException.Create("field \"" + term.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + term.Text() + ")"); } docFreq = termsEnum.DocFreq; @@ -621,7 +621,7 @@ public UnionDocsAndPositionsEnum(IBits liveDocs, AtomicReaderContext context, Te if (postings == null) { // term does exist, but has no positions - throw new InvalidOperationException("field \"" + term.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + term.Text() + ")"); + throw IllegalStateException.Create("field \"" + term.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + term.Text() + ")"); } _cost += postings.GetCost(); docsEnums.Add(postings); diff --git a/src/Lucene.Net/Search/MultiTermQuery.cs b/src/Lucene.Net/Search/MultiTermQuery.cs index fce0c69d7f..583861b772 100644 --- a/src/Lucene.Net/Search/MultiTermQuery.cs +++ b/src/Lucene.Net/Search/MultiTermQuery.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Lucene.Net.Search { @@ -253,13 +253,13 @@ public ConstantScoreAutoRewriteAnonymousClass() public override int TermCountCutoff { get => base.TermCountCutoff; // LUCENENET specific - adding getter for API consistency check - set => throw new NotSupportedException("Please create a private instance"); + set => throw UnsupportedOperationException.Create("Please create a private instance"); } public override double DocCountPercent { get => base.DocCountPercent; // LUCENENET specific - adding getter for API consistency check - set => throw new NotSupportedException("Please create a private instance"); + set => throw UnsupportedOperationException.Create("Please create a private instance"); } } @@ -269,7 +269,7 @@ public override double DocCountPercent /// protected MultiTermQuery(string field) // LUCENENET: CA1012: Abstract types should not have constructors (marked protected) { - this.m_field = field ?? throw new ArgumentNullException(nameof(field), "field must not be null"); + this.m_field = field ?? throw new ArgumentNullException(nameof(field), "field must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// diff --git a/src/Lucene.Net/Search/NumericRangeQuery.cs b/src/Lucene.Net/Search/NumericRangeQuery.cs index ebcf8cf275..c1698ea966 100644 --- a/src/Lucene.Net/Search/NumericRangeQuery.cs +++ b/src/Lucene.Net/Search/NumericRangeQuery.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using System; using System.Collections.Generic; @@ -171,7 +171,7 @@ internal NumericRangeQuery(string field, int precisionStep, NumericType dataType { if (precisionStep < 1) { - throw new ArgumentException("precisionStep must be >=1"); + throw new ArgumentOutOfRangeException(nameof(precisionStep), "precisionStep must be >=1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.precisionStep = precisionStep; this.dataType = dataType; diff --git a/src/Lucene.Net/Search/PhraseQuery.cs b/src/Lucene.Net/Search/PhraseQuery.cs index 0c590288b7..80bdf224a4 100644 --- a/src/Lucene.Net/Search/PhraseQuery.cs +++ b/src/Lucene.Net/Search/PhraseQuery.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Support; @@ -99,7 +99,7 @@ public virtual int Slop set { if (value < 0) - throw new ArgumentException("slop value cannot be negative"); + throw new ArgumentOutOfRangeException(nameof(Slop), "slop value cannot be negative"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) slop = value; } @@ -369,7 +369,7 @@ public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { if (Debugging.AssertsEnabled) Debugging.Assert(te.SeekExact(t.Bytes), "termstate found but no term exists in reader"); // term does exist, but has no positions - throw new InvalidOperationException("field \"" + t.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + t.Text() + ")"); + throw IllegalStateException.Create("field \"" + t.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + t.Text() + ")"); } postingsFreqs[i] = new PostingsAndFreq(postingsEnum, te.DocFreq, (int)outerInstance.positions[i], t); } diff --git a/src/Lucene.Net/Search/Query.cs b/src/Lucene.Net/Search/Query.cs index f19fb021ad..47759c791a 100644 --- a/src/Lucene.Net/Search/Query.cs +++ b/src/Lucene.Net/Search/Query.cs @@ -86,7 +86,7 @@ public override string ToString() /// public virtual Weight CreateWeight(IndexSearcher searcher) { - throw new NotSupportedException("Query " + this + " does not implement createWeight"); + throw UnsupportedOperationException.Create("Query " + this + " does not implement createWeight"); } /// @@ -107,7 +107,7 @@ public virtual Query Rewrite(IndexReader reader) public virtual void ExtractTerms(ISet terms) { // needs to be implemented by query subclasses - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } /// diff --git a/src/Lucene.Net/Search/QueryWrapperFilter.cs b/src/Lucene.Net/Search/QueryWrapperFilter.cs index 4802df8b86..54f548b6e2 100644 --- a/src/Lucene.Net/Search/QueryWrapperFilter.cs +++ b/src/Lucene.Net/Search/QueryWrapperFilter.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Lucene.Net.Search { @@ -41,7 +41,7 @@ public class QueryWrapperFilter : Filter /// public QueryWrapperFilter(Query query) { - this.query = query ?? throw new ArgumentNullException(nameof(query), "Query may not be null"); + this.query = query ?? throw new ArgumentNullException(nameof(query), "Query may not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } /// diff --git a/src/Lucene.Net/Search/ReferenceManager.cs b/src/Lucene.Net/Search/ReferenceManager.cs index 3dcfe3e119..37bd91e1c5 100644 --- a/src/Lucene.Net/Search/ReferenceManager.cs +++ b/src/Lucene.Net/Search/ReferenceManager.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using Lucene.Net.Support.Threading; using System; @@ -38,7 +38,7 @@ namespace Lucene.Net.Search public abstract class ReferenceManager : IDisposable where G : class //Make G nullable { - private const string REFERENCE_MANAGER_IS_CLOSED_MSG = "this ReferenceManager is closed"; + private const string REFERENCE_MANAGER_IS_CLOSED_MSG = "this ReferenceManager is disposed."; // LUCENENET NOTE: changed this to be a private volatile field // with a property to set/get it, since protected volatile @@ -62,7 +62,7 @@ private void EnsureOpen() { if (current == null) { - throw new ObjectDisposedException(this.GetType().FullName, REFERENCE_MANAGER_IS_CLOSED_MSG); + throw AlreadyClosedException.Create(this.GetType().FullName, REFERENCE_MANAGER_IS_CLOSED_MSG); } } @@ -109,7 +109,7 @@ public G Acquire() { if ((@ref = current) == null) { - throw new ObjectDisposedException(this.GetType().FullName, REFERENCE_MANAGER_IS_CLOSED_MSG); + throw AlreadyClosedException.Create(this.GetType().FullName, REFERENCE_MANAGER_IS_CLOSED_MSG); } if (TryIncRef(@ref)) { @@ -127,7 +127,7 @@ holds on to it as the actual instance. decrements the refcount without a corresponding increment since the RM assigns the new reference before counting down the reference. */ - throw new InvalidOperationException("The managed reference has already closed - this is likely a bug when the reference count is modified outside of the ReferenceManager"); + throw IllegalStateException.Create("The managed reference has already closed - this is likely a bug when the reference count is modified outside of the ReferenceManager"); } } while (true); } @@ -341,9 +341,9 @@ private void NotifyRefreshListenersRefreshed(bool didRefresh) /// public virtual void AddListener(ReferenceManager.IRefreshListener listener) { - if (listener == null) + if (listener is null) { - throw new ArgumentNullException("Listener cannot be null"); + throw new ArgumentNullException(nameof(listener), "Listener cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } refreshListeners.Add(listener); } @@ -353,9 +353,9 @@ public virtual void AddListener(ReferenceManager.IRefreshListener listener) /// public virtual void RemoveListener(ReferenceManager.IRefreshListener listener) { - if (listener == null) + if (listener is null) { - throw new ArgumentNullException("Listener cannot be null"); + throw new ArgumentNullException(nameof(listener), "Listener cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } refreshListeners.Remove(listener); } diff --git a/src/Lucene.Net/Search/SearcherLifetimeManager.cs b/src/Lucene.Net/Search/SearcherLifetimeManager.cs index 45ed9b7e3c..cc4f02adbf 100644 --- a/src/Lucene.Net/Search/SearcherLifetimeManager.cs +++ b/src/Lucene.Net/Search/SearcherLifetimeManager.cs @@ -146,7 +146,7 @@ private void EnsureOpen() { if (_closed) { - throw new ObjectDisposedException(this.GetType().FullName, "this SearcherLifetimeManager instance is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this SearcherLifetimeManager instance is disposed."); } } @@ -242,7 +242,7 @@ public PruneByAge(double maxAgeSec) { if (maxAgeSec < 0) { - throw new ArgumentException("maxAgeSec must be > 0 (got " + maxAgeSec + ")"); + throw new ArgumentOutOfRangeException("maxAgeSec must be > 0 (got " + maxAgeSec + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.maxAgeSec = maxAgeSec; } @@ -347,7 +347,7 @@ protected virtual void Dispose(bool disposing) // Make some effort to catch mis-use: if (_searchers.Count != 0) { - throw new InvalidOperationException("another thread called record while this SearcherLifetimeManager instance was being disposed; not all searchers were disposed"); + throw IllegalStateException.Create("another thread called record while this SearcherLifetimeManager instance was being disposed; not all searchers were disposed"); } } } diff --git a/src/Lucene.Net/Search/SearcherManager.cs b/src/Lucene.Net/Search/SearcherManager.cs index e0fd65d8f9..80308dcb27 100644 --- a/src/Lucene.Net/Search/SearcherManager.cs +++ b/src/Lucene.Net/Search/SearcherManager.cs @@ -176,7 +176,7 @@ public static IndexSearcher GetSearcher(SearcherFactory searcherFactory, IndexRe searcher = searcherFactory.NewSearcher(reader); if (searcher.IndexReader != reader) { - throw new InvalidOperationException("SearcherFactory must wrap exactly the provided reader (got " + searcher.IndexReader + " but expected " + reader + ")"); + throw IllegalStateException.Create("SearcherFactory must wrap exactly the provided reader (got " + searcher.IndexReader + " but expected " + reader + ")"); } success = true; } diff --git a/src/Lucene.Net/Search/Similarities/DFRSimilarity.cs b/src/Lucene.Net/Search/Similarities/DFRSimilarity.cs index 172f4b30bf..6a1f2d2df9 100644 --- a/src/Lucene.Net/Search/Similarities/DFRSimilarity.cs +++ b/src/Lucene.Net/Search/Similarities/DFRSimilarity.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Lucene.Net.Search.Similarities { @@ -108,15 +108,14 @@ public class DFRSimilarity : SimilarityBase /// Basic model of information content /// First normalization of information gain /// Second (length) normalization + /// , , + /// or is null. public DFRSimilarity(BasicModel basicModel, AfterEffect afterEffect, Normalization normalization) { - if (basicModel == null || afterEffect == null || normalization == null) - { - throw new NullReferenceException("null parameters not allowed."); - } - this.m_basicModel = basicModel; - this.m_afterEffect = afterEffect; - this.m_normalization = normalization; + // LUCENENET: Changed guard clauses from NullPointerException to ArgumentNullException + this.m_basicModel = basicModel ?? throw new ArgumentNullException(nameof(basicModel)); + this.m_afterEffect = afterEffect ?? throw new ArgumentNullException(nameof(afterEffect)); + this.m_normalization = normalization ?? throw new ArgumentNullException(nameof(normalization)); } public override float Score(BasicStats stats, float freq, float docLen) diff --git a/src/Lucene.Net/Search/SortField.cs b/src/Lucene.Net/Search/SortField.cs index fa180bdd52..53bd37e42d 100644 --- a/src/Lucene.Net/Search/SortField.cs +++ b/src/Lucene.Net/Search/SortField.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.IO; @@ -467,10 +467,10 @@ public virtual FieldComparer GetComparer(int numHits, int sortPos) return new FieldComparer.TermValComparer(numHits, field); case SortFieldType.REWRITEABLE: - throw new InvalidOperationException("SortField needs to be rewritten through Sort.rewrite(..) and SortField.rewrite(..)"); + throw IllegalStateException.Create("SortField needs to be rewritten through Sort.Rewrite(..) and SortField.Rewrite(..)"); default: - throw new InvalidOperationException("Illegal sort type: " + type); + throw IllegalStateException.Create("Illegal sort type: " + type); } } diff --git a/src/Lucene.Net/Search/Spans/NearSpansOrdered.cs b/src/Lucene.Net/Search/Spans/NearSpansOrdered.cs index da58a0976b..d9478cca16 100644 --- a/src/Lucene.Net/Search/Spans/NearSpansOrdered.cs +++ b/src/Lucene.Net/Search/Spans/NearSpansOrdered.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -111,6 +111,10 @@ public NearSpansOrdered(SpanNearQuery spanNearQuery, AtomicReaderContext context public NearSpansOrdered(SpanNearQuery spanNearQuery, AtomicReaderContext context, IBits acceptDocs, IDictionary termContexts, bool collectPayloads) { + // LUCENENET: Added guard clauses for null + if (spanNearQuery is null) + throw new ArgumentNullException(nameof(spanNearQuery)); + sorter = new InPlaceMergeSorterAnonymousClass(this); if (spanNearQuery.GetClauses().Length < 2) { diff --git a/src/Lucene.Net/Search/Spans/SpanMultiTermQueryWrapper.cs b/src/Lucene.Net/Search/Spans/SpanMultiTermQueryWrapper.cs index 453fe22ef4..c48e5d7295 100644 --- a/src/Lucene.Net/Search/Spans/SpanMultiTermQueryWrapper.cs +++ b/src/Lucene.Net/Search/Spans/SpanMultiTermQueryWrapper.cs @@ -80,7 +80,7 @@ public SpanRewriteMethod MultiTermRewriteMethod MultiTermQuery.RewriteMethod m = m_query.MultiTermRewriteMethod; if (!(m is SpanRewriteMethod spanRewriteMethod)) { - throw new NotSupportedException("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod."); + throw UnsupportedOperationException.Create("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod."); } return spanRewriteMethod; } @@ -89,7 +89,7 @@ public SpanRewriteMethod MultiTermRewriteMethod public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary termContexts) { - throw new NotSupportedException("Query should have been rewritten"); + throw UnsupportedOperationException.Create("Query should have been rewritten"); } public override string Field => m_query.Field; @@ -117,7 +117,7 @@ public override Query Rewrite(IndexReader reader) Query q = m_query.Rewrite(reader); if (!(q is SpanQuery)) { - throw new NotSupportedException("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod."); + throw UnsupportedOperationException.Create("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod."); } q.Boost = q.Boost * Boost; // multiply boost return q; diff --git a/src/Lucene.Net/Search/Spans/SpanTermQuery.cs b/src/Lucene.Net/Search/Spans/SpanTermQuery.cs index 35d70118e3..dd374e135d 100644 --- a/src/Lucene.Net/Search/Spans/SpanTermQuery.cs +++ b/src/Lucene.Net/Search/Spans/SpanTermQuery.cs @@ -164,7 +164,7 @@ public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, ID else { // term does exist, but has no positions - throw new InvalidOperationException("field \"" + m_term.Field + "\" was indexed without position data; cannot run SpanTermQuery (term=" + m_term.Text() + ")"); + throw IllegalStateException.Create("field \"" + m_term.Field + "\" was indexed without position data; cannot run SpanTermQuery (term=" + m_term.Text() + ")"); } } } diff --git a/src/Lucene.Net/Search/TermCollectingRewrite.cs b/src/Lucene.Net/Search/TermCollectingRewrite.cs index 20085c07e7..ef6b59e267 100644 --- a/src/Lucene.Net/Search/TermCollectingRewrite.cs +++ b/src/Lucene.Net/Search/TermCollectingRewrite.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; @@ -79,7 +79,7 @@ internal void CollectTerms(IndexReader reader, MultiTermQuery query, TermCollect IComparer newTermComp = termsEnum.Comparer; if (lastTermComp != null && newTermComp != null && newTermComp != lastTermComp) { - throw new Exception("term comparer should not change between segments: " + lastTermComp + " != " + newTermComp); + throw RuntimeException.Create("term comparer should not change between segments: " + lastTermComp + " != " + newTermComp); } lastTermComp = newTermComp; collector.SetReaderContext(topReaderContext, context); diff --git a/src/Lucene.Net/Search/TimeLimitingCollector.cs b/src/Lucene.Net/Search/TimeLimitingCollector.cs index cbbf842603..651d983b89 100644 --- a/src/Lucene.Net/Search/TimeLimitingCollector.cs +++ b/src/Lucene.Net/Search/TimeLimitingCollector.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using System; #if FEATURE_SERIALIZABLE_EXCEPTIONS using System.Runtime.Serialization; @@ -43,7 +43,7 @@ public class TimeLimitingCollector : ICollector #if FEATURE_SERIALIZABLE_EXCEPTIONS [Serializable] #endif - public class TimeExceededException : Exception + public class TimeExceededException : Exception, IRuntimeException // LUCENENET specific: Added IRuntimeException for identification of the Java superclass in .NET { private readonly long timeAllowed; // LUCENENET: marked readonly private readonly long timeElapsed; // LUCENENET: marked readonly @@ -57,7 +57,7 @@ internal TimeExceededException(long timeAllowed, long timeElapsed, int lastDocCo this.lastDocCollected = lastDocCollected; } - // For testing purposes + // LUCENENET: For testing purposes internal TimeExceededException(string message) : base(message) { diff --git a/src/Lucene.Net/Search/TopFieldCollector.cs b/src/Lucene.Net/Search/TopFieldCollector.cs index e8ac6ee9a1..df83744f9a 100644 --- a/src/Lucene.Net/Search/TopFieldCollector.cs +++ b/src/Lucene.Net/Search/TopFieldCollector.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.IO; @@ -1235,6 +1235,10 @@ public static TopFieldCollector Create(Sort sort, int numHits, bool fillFields, /// If there is a low-level I/O error public static TopFieldCollector Create(Sort sort, int numHits, FieldDoc after, bool fillFields, bool trackDocScores, bool trackMaxScore, bool docsScoredInOrder) { + // LUCENENET specific: Added guard clause for null + if (sort is null) + throw new ArgumentNullException(nameof(sort)); + if (sort.fields.Length == 0) { throw new ArgumentException("Sort must contain at least one field"); @@ -1247,7 +1251,7 @@ public static TopFieldCollector Create(Sort sort, int numHits, FieldDoc after, b FieldValueHitQueue queue = FieldValueHitQueue.Create(sort.fields, numHits); - if (after == null) + if (after is null) { if (queue.Comparers.Length == 1) { @@ -1319,12 +1323,12 @@ public static TopFieldCollector Create(Sort sort, int numHits, FieldDoc after, b { if (after.Fields == null) { - throw new ArgumentException("after.fields wasn't set; you must pass fillFields=true for the previous search"); + throw new ArgumentException("after.Fields wasn't set; you must pass fillFields=true for the previous search"); } if (after.Fields.Length != sort.GetSort().Length) { - throw new ArgumentException("after.fields has " + after.Fields.Length + " values but sort has " + sort.GetSort().Length); + throw new ArgumentException("after.Fields has " + after.Fields.Length + " values but sort has " + sort.GetSort().Length); } return new PagingFieldCollector(queue, after, numHits, fillFields, trackDocScores, trackMaxScore); diff --git a/src/Lucene.Net/Search/TopScoreDocCollector.cs b/src/Lucene.Net/Search/TopScoreDocCollector.cs index 4839499547..0b24902733 100644 --- a/src/Lucene.Net/Search/TopScoreDocCollector.cs +++ b/src/Lucene.Net/Search/TopScoreDocCollector.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Runtime.CompilerServices; @@ -278,7 +278,7 @@ public static TopScoreDocCollector Create(int numHits, ScoreDoc after, bool docs { if (numHits <= 0) { - throw new ArgumentException("numHits must be > 0; please use TotalHitCountCollector if you just need the total hit count"); + throw new ArgumentOutOfRangeException(nameof(numHits), "numHits must be > 0; please use TotalHitCountCollector if you just need the total hit count"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (docsScoredInOrder) diff --git a/src/Lucene.Net/Search/Weight.cs b/src/Lucene.Net/Search/Weight.cs index 3168f0513d..be55788288 100644 --- a/src/Lucene.Net/Search/Weight.cs +++ b/src/Lucene.Net/Search/Weight.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; namespace Lucene.Net.Search @@ -149,7 +149,8 @@ internal class DefaultBulkScorer : BulkScorer public DefaultBulkScorer(Scorer scorer) { - this.scorer = scorer ?? throw new NullReferenceException(); + // LUCENENET: Changed from NullPointerException to ArgumentNullException + this.scorer = scorer ?? throw new ArgumentNullException(nameof(scorer)); } public override bool Score(ICollector collector, int max) diff --git a/src/Lucene.Net/Store/AlreadyClosedException.cs b/src/Lucene.Net/Store/AlreadyClosedException.cs index 3e2f7e345b..cf30372b11 100644 --- a/src/Lucene.Net/Store/AlreadyClosedException.cs +++ b/src/Lucene.Net/Store/AlreadyClosedException.cs @@ -1,8 +1,12 @@ -// LUCENENET specific - commented this because we already have an ObjectDisposedException in .NET. -// This is just reinventing the wheel. ObjectDisposedException, like AlreadyClosedException, subclasses -// InvalidOperationException, so it makes a good replacement. - +// LUCENENET specific - commented this because we already have an ObjectDisposedException in .NET. +// This is just reinventing the wheel. However ObjectDisposedException subclasses InvalidOperationException, +// while AlreadyClosedException, subclasses IOException, so we patch this behavior in ExceptionExtensions. +// There is a duplicate type in the Lucene namespace that acts as a static factory to create ObjectDisposedException, +// which is intended to make porting efforts easier. //using System; +//#if FEATURE_SERIALIZABLE_EXCEPTIONS +//using System.Runtime.Serialization; +//#endif //namespace Lucene.Net.Store //{ @@ -32,11 +36,28 @@ //#if FEATURE_SERIALIZABLE_EXCEPTIONS // [Serializable] //#endif -// public class AlreadyClosedException : InvalidOperationException +// [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1032:Implement standard exception constructors", Justification = "ObjectDisposedExcption already violates this rule by not having a default constructor.")] +// internal class AlreadyClosedException : ObjectDisposedException // LUCENENET specific: marked internal, as we only want users to catch ObjectDisposedException // { // public AlreadyClosedException(string message) // : base(message) // { // } + +// public AlreadyClosedException(string message, Exception innerException) : base(message, innerException) // LUCENENET: CA1032: Implement standard exception constructors +// { +// } + +//#if FEATURE_SERIALIZABLE_EXCEPTIONS +// /// +// /// Initializes a new instance of this class with serialized data. +// /// +// /// The that holds the serialized object data about the exception being thrown. +// /// The that contains contextual information about the source or destination. +// protected AlreadyClosedException(SerializationInfo info, StreamingContext context) +// : base(info, context) +// { +// } +//#endif // } //} \ No newline at end of file diff --git a/src/Lucene.Net/Store/BaseDirectory.cs b/src/Lucene.Net/Store/BaseDirectory.cs index 2502d3c2ed..d1fc1d497d 100644 --- a/src/Lucene.Net/Store/BaseDirectory.cs +++ b/src/Lucene.Net/Store/BaseDirectory.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; namespace Lucene.Net.Store @@ -77,7 +77,7 @@ protected internal override sealed void EnsureOpen() { if (!IsOpen) { - throw new ObjectDisposedException(this.GetType().FullName, "this Directory is closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "this Directory is disposed."); } } } diff --git a/src/Lucene.Net/Store/BufferedChecksumIndexInput.cs b/src/Lucene.Net/Store/BufferedChecksumIndexInput.cs index 639a7549eb..9353650548 100644 --- a/src/Lucene.Net/Store/BufferedChecksumIndexInput.cs +++ b/src/Lucene.Net/Store/BufferedChecksumIndexInput.cs @@ -70,7 +70,7 @@ public override long GetFilePointer() public override object Clone() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } \ No newline at end of file diff --git a/src/Lucene.Net/Store/BufferedIndexInput.cs b/src/Lucene.Net/Store/BufferedIndexInput.cs index 6da7586c52..720af9d6e6 100644 --- a/src/Lucene.Net/Store/BufferedIndexInput.cs +++ b/src/Lucene.Net/Store/BufferedIndexInput.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.IO; using System.Runtime.CompilerServices; @@ -129,7 +129,7 @@ private static void CheckBufferSize(int bufferSize) // LUCENENET: CA1822: Mark m { if (bufferSize <= 0) { - throw new ArgumentException("bufferSize must be greater than 0 (got " + bufferSize + ")"); + throw new ArgumentOutOfRangeException("bufferSize must be greater than 0 (got " + bufferSize + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } } @@ -172,7 +172,7 @@ public override sealed void ReadBytes(byte[] b, int offset, int len, bool useBuf { // Throw an exception when refill() could not read len bytes: Buffer.BlockCopy(m_buffer, 0, b, offset, bufferLength); - throw new EndOfStreamException("read past EOF: " + this); + throw EOFException.Create("read past EOF: " + this); } else { @@ -192,7 +192,7 @@ public override sealed void ReadBytes(byte[] b, int offset, int len, bool useBuf long after = bufferStart + bufferPosition + len; if (after > Length) { - throw new EndOfStreamException("read past EOF: " + this); + throw EOFException.Create("read past EOF: " + this); } ReadInternal(b, offset, len); bufferStart = after; @@ -378,7 +378,7 @@ private void Refill() int newLength = (int)(end - start); if (newLength <= 0) { - throw new EndOfStreamException("read past EOF: " + this); + throw EOFException.Create("read past EOF: " + this); } if (m_buffer == null) diff --git a/src/Lucene.Net/Store/BufferedIndexOutput.cs b/src/Lucene.Net/Store/BufferedIndexOutput.cs index e76d2ddfcb..776b952ec9 100644 --- a/src/Lucene.Net/Store/BufferedIndexOutput.cs +++ b/src/Lucene.Net/Store/BufferedIndexOutput.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using System; using System.Runtime.CompilerServices; @@ -58,7 +58,7 @@ internal BufferedIndexOutput(int bufferSize, CRC32 crc) { if (bufferSize <= 0) { - throw new ArgumentException("bufferSize must be greater than 0 (got " + bufferSize + ")"); + throw new ArgumentOutOfRangeException("bufferSize must be greater than 0 (got " + bufferSize + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.bufferSize = bufferSize; // LUCENENET: We lazy-load the buffer, so we don't force all subclasses to allocate it diff --git a/src/Lucene.Net/Store/ByteArrayDataInput.cs b/src/Lucene.Net/Store/ByteArrayDataInput.cs index 562355ef52..e4a50ab0c9 100644 --- a/src/Lucene.Net/Store/ByteArrayDataInput.cs +++ b/src/Lucene.Net/Store/ByteArrayDataInput.cs @@ -153,7 +153,7 @@ public override int ReadVInt32() { return i; } - throw new Exception("Invalid VInt32 detected (too many bits)"); + throw RuntimeException.Create("Invalid VInt32 detected (too many bits)"); } /// @@ -215,7 +215,7 @@ public override long ReadVInt64() { return i; } - throw new Exception("Invalid VInt64 detected (negative values disallowed)"); + throw RuntimeException.Create("Invalid VInt64 detected (negative values disallowed)"); } // NOTE: AIOOBE not EOF if you read too much diff --git a/src/Lucene.Net/Store/ByteBufferIndexInput.cs b/src/Lucene.Net/Store/ByteBufferIndexInput.cs index e1381df838..0b182d6f0d 100644 --- a/src/Lucene.Net/Store/ByteBufferIndexInput.cs +++ b/src/Lucene.Net/Store/ByteBufferIndexInput.cs @@ -1,7 +1,6 @@ using J2N.IO; using J2N.Numerics; using Lucene.Net.Diagnostics; -using Lucene.Net.Util.Fst; using System; using System.IO; using System.Runtime.CompilerServices; @@ -124,7 +123,7 @@ public override sealed byte ReadByte() curBufIndex++; if (curBufIndex >= buffers.Length) { - throw new EndOfStreamException("read past EOF: " + this); + throw EOFException.Create("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.Position = 0; @@ -152,7 +151,7 @@ public override sealed void ReadBytes(byte[] b, int offset, int len) curBufIndex++; if (curBufIndex >= buffers.Length) { - throw new EndOfStreamException("read past EOF: " + this); + throw EOFException.Create("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.Position = 0; @@ -217,35 +216,39 @@ public override sealed long GetFilePointer() public override sealed void Seek(long pos) { + // LUCENENET: Refactored to avoid calls on invalid conditions instead of + // catching and re-throwing exceptions in the normal workflow. + EnsureOpen(); // necessary in case offset != 0 and pos < 0, but pos >= -offset if (pos < 0L) { - throw new ArgumentException("Seeking to negative position: " + this); + throw new ArgumentOutOfRangeException("Seeking to negative position: " + this); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } pos += offset; // we use >> here to preserve negative, so we will catch AIOOBE, // in case pos + offset overflows. int bi = (int)(pos >> chunkSizePower); - try - { - ByteBuffer b = buffers[bi]; - b.Position = ((int)(pos & chunkSizeMask)); - // write values, on exception all is unchanged - this.curBufIndex = bi; - this.curBuf = b; - } - catch (IndexOutOfRangeException aioobe) - { - throw new EndOfStreamException("seek past EOF: " + this, aioobe); - } - catch (ArgumentException iae) - { - throw new EndOfStreamException("seek past EOF: " + this, iae); - } - catch (NullReferenceException npe) - { - throw new ObjectDisposedException("Already closed: " + this, npe); - } + + // LUCENENET: Defensive programming so we don't get an IndexOutOfRangeException + // when reading from buffers. + if (bi < 0 || bi >= buffers.Length) + throw EOFException.Create("seek past EOF: " + this); + + ByteBuffer b = buffers[bi]; + int newPosition = (int)(pos & chunkSizeMask); + + // LUCENENET: Defensive programming so we don't get an ArgumentOutOfRangeException + // when setting b.Position. + if (newPosition < 0 || newPosition > b.Limit) + throw EOFException.Create("seek past EOF: " + this); + + b.Position = newPosition; + // write values, on exception all is unchanged + this.curBufIndex = bi; + this.curBuf = b; + + // LUCENENET: Already checked buffers to see if it was null in EnsureOpen(). + // If we get a NullReferenceException we definitely need it to be thrown so it is known. } public override sealed long Length => length; @@ -257,9 +260,9 @@ public override sealed object Clone() { clone.Seek(GetFilePointer()); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception("Should never happen: " + this, ioe); + throw RuntimeException.Create("Should never happen: " + this, ioe); } return clone; @@ -270,9 +273,12 @@ public override sealed object Clone() /// public ByteBufferIndexInput Slice(string sliceDescription, long offset, long length) { + // LUCENENET: Refactored to avoid calls on invalid conditions instead of + // catching and re-throwing exceptions in the normal workflow. + EnsureOpen(); if (isClone) // well we could, but this is stupid { - throw new InvalidOperationException("cannot slice() " + sliceDescription + " from a cloned IndexInput: " + this); + throw IllegalStateException.Create("cannot Slice() " + sliceDescription + " from a cloned IndexInput: " + this); } ByteBufferIndexInput clone = BuildSlice(offset, length); clone.sliceDescription = sliceDescription; @@ -280,9 +286,9 @@ public ByteBufferIndexInput Slice(string sliceDescription, long offset, long len { clone.Seek(0L); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new Exception("Should never happen: " + this, ioe); + throw RuntimeException.Create("Should never happen: " + this, ioe); } return clone; @@ -290,11 +296,15 @@ public ByteBufferIndexInput Slice(string sliceDescription, long offset, long len private ByteBufferIndexInput BuildSlice(long offset, long length) { - if (buffers == null) - { - throw new ObjectDisposedException(this.GetType().FullName, "Already closed: " + this); - } - if (offset < 0 || length < 0 || offset + length > this.length) + // LUCENENET: Refactored to avoid calls on invalid conditions instead of + // catching and re-throwing exceptions in the normal workflow. + EnsureOpen(); + // LUCENENET: Added .NET-sytle guard clauses that throw ArgumementOutOfRangeException + if (offset < 0) + throw new ArgumentOutOfRangeException(nameof(offset), "offset may not be negative."); + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), "length may not be negative."); + if (offset + length > this.length) { throw new ArgumentException("slice() " + sliceDescription + " out of bounds: offset=" + offset + ",length=" + length + ",fileLength=" + this.length + ": " + this); } @@ -356,9 +366,9 @@ private void UnsetBuffers() // for control flow, we check whether we are disposed first. private void EnsureOpen() { - if (buffers == null || curBuf == null) + if (buffers is null) { - throw new ObjectDisposedException(this.GetType().FullName, "Already closed: " + this); + throw AlreadyClosedException.Create(this.GetType().FullName, "Already disposed: " + this); } } diff --git a/src/Lucene.Net/Store/CheckSumIndexInput.cs b/src/Lucene.Net/Store/CheckSumIndexInput.cs index 16dcc2f307..ab9a0920e7 100644 --- a/src/Lucene.Net/Store/CheckSumIndexInput.cs +++ b/src/Lucene.Net/Store/CheckSumIndexInput.cs @@ -51,7 +51,7 @@ public override void Seek(long pos) long skip = pos - GetFilePointer(); if (skip < 0) { - throw new InvalidOperationException(this.GetType() + " cannot seek backwards"); + throw IllegalStateException.Create(this.GetType() + " cannot seek backwards"); } SkipBytes(skip); } diff --git a/src/Lucene.Net/Store/CompoundFileDirectory.cs b/src/Lucene.Net/Store/CompoundFileDirectory.cs index c887250090..57650456ab 100644 --- a/src/Lucene.Net/Store/CompoundFileDirectory.cs +++ b/src/Lucene.Net/Store/CompoundFileDirectory.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using J2N.Numerics; using Lucene.Net.Diagnostics; using Lucene.Net.Support; @@ -140,7 +140,7 @@ public CompoundFileDirectory(Directory directory, string fileName, IOContext con /// Helper method that reads CFS entries from an input stream private static IDictionary ReadEntries(IndexInputSlicer handle, Directory dir, string name) { - IOException priorE = null; + Exception priorE = null; // LUCENENET: No need to cast to IOExcpetion IndexInput stream = null; ChecksumIndexInput entriesStream = null; // read the first VInt. If it is negative, it's the version number @@ -201,7 +201,7 @@ private static IDictionary ReadEntries(IndexInputSlicer handl } return mapping; } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { priorE = ioe; } @@ -210,7 +210,7 @@ private static IDictionary ReadEntries(IndexInputSlicer handl IOUtils.DisposeWhileHandlingException(priorE, stream, entriesStream); } // this is needed until Java 7's real try-with-resources: - throw new InvalidOperationException("impossible to get here"); + throw AssertionError.Create("impossible to get here"); } private static IDictionary ReadLegacyEntries(IndexInput stream, int firstInt) @@ -366,7 +366,7 @@ public override bool FileExists(string name) /// always: not supported by CFS public override void DeleteFile(string name) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } /// @@ -376,7 +376,7 @@ public override void DeleteFile(string name) public void RenameFile(string from, string to) #pragma warning restore IDE0060, CA1822 // Remove unused parameter, Mark members as static { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } /// @@ -405,7 +405,7 @@ public override IndexOutput CreateOutput(string name, IOContext context) public override void Sync(ICollection names) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } /// @@ -413,7 +413,7 @@ public override void Sync(ICollection names) /// always: not supported by CFS public override Lock MakeLock(string name) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public override IndexInputSlicer CreateSlicer(string name, IOContext context) diff --git a/src/Lucene.Net/Store/CompoundFileWriter.cs b/src/Lucene.Net/Store/CompoundFileWriter.cs index 69023aa47f..e24720b82d 100644 --- a/src/Lucene.Net/Store/CompoundFileWriter.cs +++ b/src/Lucene.Net/Store/CompoundFileWriter.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using J2N.Threading.Atomic; using Lucene.Net.Diagnostics; using System; @@ -91,7 +91,8 @@ private sealed class FileEntry /// if or is null internal CompoundFileWriter(Directory dir, string name) { - // LUCENENET specific - changed order to take advantage of throw expression + // LUCENENET specific - changed order to take advantage of throw expression and + // changed from IllegalArgumentException to ArgumentNullException (.NET convention) directory = dir ?? throw new ArgumentNullException(nameof(directory), $"{nameof(directory)} cannot be null"); dataFileName = name ?? throw new ArgumentNullException(nameof(name), $"{nameof(name)} cannot be null"); entryTableName = IndexFileNames.SegmentFileName(IndexFileNames.StripExtension(name), "", IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION); @@ -142,7 +143,7 @@ public void Dispose() { return; } - IOException priorException = null; + Exception priorException = null; // LUCENENET: No need to cast to IOExcpetion IndexOutput entryTableOut = null; // TODO this code should clean up after itself // (remove partial .cfs/.cfe) @@ -150,7 +151,7 @@ public void Dispose() { if (pendingEntries.Count > 0 || outputTaken) { - throw new InvalidOperationException("CFS has pending open files"); + throw IllegalStateException.Create("CFS has pending open files"); } closed = true; // open the compound stream @@ -158,7 +159,7 @@ public void Dispose() if (Debugging.AssertsEnabled) Debugging.Assert(dataOut != null); CodecUtil.WriteFooter(dataOut); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { priorException = e; } @@ -171,7 +172,7 @@ public void Dispose() entryTableOut = directory.CreateOutput(entryTableName, IOContext.DEFAULT); WriteEntryTable(entries.Values, entryTableOut); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { priorException = e; } @@ -186,7 +187,7 @@ private void EnsureOpen() { if (closed) { - throw new ObjectDisposedException(this.GetType().FullName, "CFS Directory is already closed"); + throw AlreadyClosedException.Create(this.GetType().FullName, "CFS Directory is already disposed."); } } diff --git a/src/Lucene.Net/Store/DataInput.cs b/src/Lucene.Net/Store/DataInput.cs index 258ed5e0b1..0db8c27469 100644 --- a/src/Lucene.Net/Store/DataInput.cs +++ b/src/Lucene.Net/Store/DataInput.cs @@ -315,7 +315,7 @@ public virtual void SkipBytes(long numBytes) { if (numBytes < 0) { - throw new ArgumentException("numBytes must be >= 0, got " + numBytes); + throw new ArgumentOutOfRangeException("numBytes must be >= 0, got " + numBytes); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (skipBuffer == null) { diff --git a/src/Lucene.Net/Store/Directory.cs b/src/Lucene.Net/Store/Directory.cs index c460ce34c1..51726d20b3 100644 --- a/src/Lucene.Net/Store/Directory.cs +++ b/src/Lucene.Net/Store/Directory.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using System; using System.Collections.Generic; using System.IO; @@ -195,14 +195,14 @@ public virtual void Copy(Directory to, string src, string dest, IOContext contex { IndexOutput os = null; IndexInput @is = null; - IOException priorException = null; + Exception priorException = null; // LUCENENET: No need to cast to IOExcpetion try { os = to.CreateOutput(dest, context); @is = OpenInput(src, context); os.CopyBytes(@is, @is.Length); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { priorException = ioe; } @@ -222,7 +222,7 @@ public virtual void Copy(Directory to, string src, string dest, IOContext contex { to.DeleteFile(dest); } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { } } @@ -357,7 +357,7 @@ protected override void ReadInternal(byte[] b, int offset, int len) long start = GetFilePointer(); if (start + len > length) { - throw new Exception("read past EOF: " + this); + throw EOFException.Create("read past EOF: " + this); } @base.Seek(fileOffset + start); @base.ReadBytes(b, offset, len, false); diff --git a/src/Lucene.Net/Store/FSDirectory.cs b/src/Lucene.Net/Store/FSDirectory.cs index 8b03dd8549..cccdd41b9d 100644 --- a/src/Lucene.Net/Store/FSDirectory.cs +++ b/src/Lucene.Net/Store/FSDirectory.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support; +using Lucene.Net.Support; using Lucene.Net.Support.IO; using System; using System.Collections.Generic; @@ -408,9 +408,9 @@ public override string GetLockID() { dirName = m_directory.GetCanonicalPath(); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(e); } int digest = 0; @@ -458,7 +458,7 @@ public int ReadChunkSize set { if (value <= 0) - throw new ArgumentException("chunkSize must be positive"); + throw new ArgumentOutOfRangeException(nameof(ReadChunkSize), "chunkSize must be positive"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) this.chunkSize = value; } @@ -499,8 +499,9 @@ public FSIndexOutput(FSDirectory parent, string name) /// public override void WriteByte(byte b) { + // LUCENENET specific: Guard to ensure we aren't disposed. if (!isOpen) - throw new ObjectDisposedException(nameof(FSIndexOutput)); + throw AlreadyClosedException.Create(this.GetType().FullName, "This FSIndexOutput is disposed."); crc.Update(b); file.WriteByte(b); @@ -509,8 +510,9 @@ public override void WriteByte(byte b) /// public override void WriteBytes(byte[] b, int offset, int length) { + // LUCENENET specific: Guard to ensure we aren't disposed. if (!isOpen) - throw new ObjectDisposedException(nameof(FSIndexOutput)); + throw AlreadyClosedException.Create(this.GetType().FullName, "This FSIndexOutput is disposed."); crc.Update(b, offset, length); file.Write(b, offset, length); @@ -519,8 +521,9 @@ public override void WriteBytes(byte[] b, int offset, int length) /// protected internal override void FlushBuffer(byte[] b, int offset, int size) { + // LUCENENET specific: Guard to ensure we aren't disposed. if (!isOpen) - throw new ObjectDisposedException(nameof(FSIndexOutput)); + throw AlreadyClosedException.Create(this.GetType().FullName, "This FSIndexOutput is disposed."); crc.Update(b, offset, size); file.Write(b, offset, size); @@ -530,8 +533,9 @@ protected internal override void FlushBuffer(byte[] b, int offset, int size) [MethodImpl(MethodImplOptions.NoInlining)] public override void Flush() { + // LUCENENET specific: Guard to ensure we aren't disposed. if (!isOpen) - throw new ObjectDisposedException(nameof(FSIndexOutput)); + throw AlreadyClosedException.Create(this.GetType().FullName, "This FSIndexOutput is disposed."); file.Flush(); } @@ -545,12 +549,12 @@ protected override void Dispose(bool disposing) // only close the file if it has not been closed yet if (isOpen) { - IOException priorE = null; + Exception priorE = null; // LUCENENET: No need to cast to IOExcpetion try { file.Flush(flushToDisk: true); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { priorE = ioe; } @@ -568,8 +572,9 @@ protected override void Dispose(bool disposing) [Obsolete("(4.1) this method will be removed in Lucene 5.0")] public override void Seek(long pos) { + // LUCENENET specific: Guard to ensure we aren't disposed. if (!isOpen) - throw new ObjectDisposedException(nameof(FSIndexOutput)); + throw AlreadyClosedException.Create(this.GetType().FullName, "This FSIndexOutput is disposed."); file.Seek(pos, SeekOrigin.Begin); } diff --git a/src/Lucene.Net/Store/FSLockFactory.cs b/src/Lucene.Net/Store/FSLockFactory.cs index 646458cf21..96536d0dbb 100644 --- a/src/Lucene.Net/Store/FSLockFactory.cs +++ b/src/Lucene.Net/Store/FSLockFactory.cs @@ -41,7 +41,7 @@ protected internal void SetLockDir(DirectoryInfo lockDir) { if (this.m_lockDir != null) { - throw new InvalidOperationException("You can set the lock directory for this factory only once."); + throw IllegalStateException.Create("You can set the lock directory for this factory only once."); } this.m_lockDir = lockDir; } diff --git a/src/Lucene.Net/Store/FileSwitchDirectory.cs b/src/Lucene.Net/Store/FileSwitchDirectory.cs index 49b734fd67..997b95b737 100644 --- a/src/Lucene.Net/Store/FileSwitchDirectory.cs +++ b/src/Lucene.Net/Store/FileSwitchDirectory.cs @@ -1,7 +1,8 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using System; using System.Collections.Generic; using System.IO; +using System.Runtime.ExceptionServices; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Store @@ -82,7 +83,7 @@ public override string[] ListAll() // but if one underlying delegate is an FSDir and mkdirs() has not // yet been called, because so far everything is written to the other, // in this case, we don't want to throw a NoSuchDirectoryException - DirectoryNotFoundException exc = null; + Exception exc = null; // LUCENENET: No need to cast to DirectoryNotFoundException try { foreach (string f in primaryDir.ListAll()) @@ -90,7 +91,7 @@ public override string[] ListAll() files.Add(f); } } - catch (DirectoryNotFoundException e) + catch (Exception e) when (e.IsNoSuchDirectoryException()) { exc = e; } @@ -102,13 +103,13 @@ public override string[] ListAll() files.Add(f); } } - catch (DirectoryNotFoundException /*e*/) + catch (Exception e) when (e.IsNoSuchDirectoryException()) { // we got NoSuchDirectoryException from both dirs // rethrow the first. if (exc != null) { - throw exc; + ExceptionDispatchInfo.Capture(exc).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } // we got NoSuchDirectoryException from the secondary, // and the primary is empty. @@ -122,7 +123,7 @@ public override string[] ListAll() if (exc != null && files.Count == 0) { - throw exc; + ExceptionDispatchInfo.Capture(exc).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } return files.ToArray(); } diff --git a/src/Lucene.Net/Store/IndexInput.cs b/src/Lucene.Net/Store/IndexInput.cs index a120138e51..a3b2fe014a 100644 --- a/src/Lucene.Net/Store/IndexInput.cs +++ b/src/Lucene.Net/Store/IndexInput.cs @@ -45,6 +45,7 @@ public abstract class IndexInput : DataInput, IDisposable // LUCENENET specific: /// protected IndexInput(string resourceDescription) { + // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) this.resourceDescription = resourceDescription ?? throw new ArgumentNullException(nameof(resourceDescription), $"{nameof(resourceDescription)} must not be null"); } diff --git a/src/Lucene.Net/Store/InputStreamDataInput.cs b/src/Lucene.Net/Store/InputStreamDataInput.cs index fab212a7bd..d3b804019a 100644 --- a/src/Lucene.Net/Store/InputStreamDataInput.cs +++ b/src/Lucene.Net/Store/InputStreamDataInput.cs @@ -37,7 +37,7 @@ public override byte ReadByte() int v = _reader.ReadByte(); if (v == -1) { - throw new EndOfStreamException(); + throw EOFException.Create(); } return (byte)v; } @@ -50,7 +50,7 @@ public override void ReadBytes(byte[] b, int offset, int len) if (cnt < 0) { // Partially read the input, but no more data available in the stream. - throw new EndOfStreamException(); + throw EOFException.Create(); } len -= cnt; offset += cnt; diff --git a/src/Lucene.Net/Store/Lock.cs b/src/Lucene.Net/Store/Lock.cs index 78c465cdcf..4ee94d0584 100644 --- a/src/Lucene.Net/Store/Lock.cs +++ b/src/Lucene.Net/Store/Lock.cs @@ -107,7 +107,7 @@ public static With NewAnonymous(Lock @lock, int lockWaitTimeout, Func d /// to retry forever /// true if lock was obtained /// if lock wait times out - /// if is + /// if is /// out of bounds /// if throws public bool Obtain(long lockWaitTimeout) @@ -116,7 +116,7 @@ public bool Obtain(long lockWaitTimeout) bool locked = Obtain(); if (lockWaitTimeout < 0 && lockWaitTimeout != LOCK_OBTAIN_WAIT_FOREVER) { - throw new ArgumentException("lockWaitTimeout should be LOCK_OBTAIN_WAIT_FOREVER or a non-negative number (got " + lockWaitTimeout + ")"); + throw new ArgumentOutOfRangeException("lockWaitTimeout should be LOCK_OBTAIN_WAIT_FOREVER or a non-negative number (got " + lockWaitTimeout + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } long maxSleepCount = lockWaitTimeout / LOCK_POLL_INTERVAL; diff --git a/src/Lucene.Net/Store/LockStressTest.cs b/src/Lucene.Net/Store/LockStressTest.cs index e4cfa279fa..f0997517f1 100644 --- a/src/Lucene.Net/Store/LockStressTest.cs +++ b/src/Lucene.Net/Store/LockStressTest.cs @@ -64,7 +64,7 @@ public static void Main(string[] args) if (myID < 0 || myID > 255) { - throw new ArgumentException("ID must be a unique int 0..255"); + throw new ArgumentOutOfRangeException("ID", "ID must be a unique int 0..255"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) //Console.WriteLine("myID must be a unique int 0..255"); //Environment.Exit(1); } @@ -83,7 +83,7 @@ public static void Main(string[] args) try { c = Type.GetType(lockFactoryClassName); - if (c == null) + if (c is null) { // LUCENENET: try again, this time with the Store namespace c = Type.GetType("Lucene.Net.Store." + lockFactoryClassName); @@ -99,18 +99,15 @@ public static void Main(string[] args) { lockFactory = (LockFactory)Activator.CreateInstance(c); } - catch (UnauthorizedAccessException e) + catch (Exception e) when (e.IsIllegalAccessException() || e.IsInstantiationException() || e.IsClassNotFoundException()) { throw new IOException("Cannot instantiate lock factory " + lockFactoryClassName, e); } - catch (InvalidCastException e) + // LUCENENET specific - added more explicit exception message in this case + catch (Exception e) when (e.IsClassCastException()) { throw new IOException("unable to cast LockClass " + lockFactoryClassName + " instance to a LockFactory", e); } - catch (Exception e) - { - throw new IOException("InstantiationException when instantiating LockClass " + lockFactoryClassName, e); - } DirectoryInfo lockDir = new DirectoryInfo(lockDirName); diff --git a/src/Lucene.Net/Store/LockVerifyServer.cs b/src/Lucene.Net/Store/LockVerifyServer.cs index 7d17bc0504..edfa6f03c5 100644 --- a/src/Lucene.Net/Store/LockVerifyServer.cs +++ b/src/Lucene.Net/Store/LockVerifyServer.cs @@ -1,4 +1,4 @@ -using J2N.Threading; +using J2N.Threading; using Lucene.Net.Util; using System; using System.Globalization; @@ -150,7 +150,7 @@ public override void Run() if (currentLock != -1) { lockedID[0] = -2; - throw new InvalidOperationException("id " + id + " got lock, but " + currentLock + " already holds the lock"); + throw IllegalStateException.Create("id " + id + " got lock, but " + currentLock + " already holds the lock"); } lockedID[0] = id; break; @@ -160,28 +160,26 @@ public override void Run() if (currentLock != id) { lockedID[0] = -2; - throw new InvalidOperationException("id " + id + " released the lock, but " + currentLock + " is the one holding the lock"); + throw IllegalStateException.Create("id " + id + " released the lock, but " + currentLock + " is the one holding the lock"); } lockedID[0] = -1; break; default: - throw new Exception("Unrecognized command: " + command); + throw RuntimeException.Create("Unrecognized command: " + command); } intWriter.Write((byte)command); stream.Flush(); } } } - catch (IOException ioe) + catch (Exception e) when (e.IsRuntimeException() || e.IsError()) { - throw new Exception(ioe.ToString(), ioe); + 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 e) + catch (Exception ioe) when (ioe.IsException()) { - // LUCENENET NOTE: We need to throw a new exception - // to ensure this is Exception and not some other type. - throw new Exception(e.ToString(), e); + throw RuntimeException.Create(ioe); } finally { diff --git a/src/Lucene.Net/Store/MMapDirectory.cs b/src/Lucene.Net/Store/MMapDirectory.cs index 61f84049c0..7c75c54d11 100644 --- a/src/Lucene.Net/Store/MMapDirectory.cs +++ b/src/Lucene.Net/Store/MMapDirectory.cs @@ -108,7 +108,7 @@ public MMapDirectory(DirectoryInfo path, LockFactory lockFactory, int maxChunkSi { if (maxChunkSize <= 0) { - throw new ArgumentException("Maximum chunk size for mmap must be >0"); + throw new ArgumentOutOfRangeException(nameof(maxChunkSize), "Maximum chunk size for mmap must be > 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.chunkSizePower = 31 - maxChunkSize.LeadingZeroCount(); if (Debugging.AssertsEnabled) Debugging.Assert(this.chunkSizePower >= 0 && this.chunkSizePower <= 30); @@ -234,7 +234,7 @@ public sealed class MMapIndexInput : ByteBufferIndexInput internal MMapIndexInput(MMapDirectory outerInstance, string resourceDescription, FileStream fc) : base(resourceDescription, null, fc.Length, outerInstance.chunkSizePower, true) { - this.fc = fc ?? throw new ArgumentNullException(nameof(fc)); + this.fc = fc ?? throw new ArgumentNullException(nameof(fc)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) this.SetBuffers(outerInstance.Map(this, fc, 0, fc.Length)); } diff --git a/src/Lucene.Net/Store/NIOFSDirectory.cs b/src/Lucene.Net/Store/NIOFSDirectory.cs index 12487b2e3c..3ffb457c28 100644 --- a/src/Lucene.Net/Store/NIOFSDirectory.cs +++ b/src/Lucene.Net/Store/NIOFSDirectory.cs @@ -1,4 +1,4 @@ -using J2N.IO; +using J2N.IO; using Lucene.Net.Diagnostics; using Lucene.Net.Support.IO; using System; @@ -150,9 +150,9 @@ public override IndexInput OpenFullSlice() { return OpenSlice("full-slice", 0, descriptor.Length); } - catch (IOException ex) + catch (Exception ex) when (ex.IsIOException()) { - throw new Exception(ex.ToString(), ex); + throw RuntimeException.Create(ex); } } } @@ -250,7 +250,7 @@ protected override void ReadInternal(byte[] b, int offset, int len) if (pos + len > m_end) { - throw new EndOfStreamException("read past EOF: " + this); + throw EOFException.Create("read past EOF: " + this); } try @@ -263,7 +263,7 @@ protected override void ReadInternal(byte[] b, int offset, int len) int i = m_channel.Read(bb, pos); if (i <= 0) // be defensive here, even though we checked before hand, something could have changed { - throw new Exception("read past EOF: " + this + " off: " + offset + " len: " + len + " pos: " + pos + " chunkLen: " + readLength + " end: " + m_end); + throw EOFException.Create("read past EOF: " + this + " off: " + offset + " len: " + len + " pos: " + pos + " chunkLen: " + readLength + " end: " + m_end); } pos += i; readOffset += i; @@ -271,7 +271,7 @@ protected override void ReadInternal(byte[] b, int offset, int len) } if (Debugging.AssertsEnabled) Debugging.Assert(readLength == 0); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { throw new IOException(ioe.ToString() + ": " + this, ioe); } diff --git a/src/Lucene.Net/Store/NRTCachingDirectory.cs b/src/Lucene.Net/Store/NRTCachingDirectory.cs index f8bf8ed841..ba50abfc7f 100644 --- a/src/Lucene.Net/Store/NRTCachingDirectory.cs +++ b/src/Lucene.Net/Store/NRTCachingDirectory.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using System; using System.Collections.Generic; using System.IO; @@ -141,7 +141,7 @@ public override string[] ListAll() files.Add(f); } } - catch (DirectoryNotFoundException /*ex*/) + catch (Exception ex) when (ex.IsNoSuchDirectoryException()) { // however, if there are no cached files, then the directory truly // does not "exist" @@ -231,7 +231,7 @@ public override IndexOutput CreateOutput(string name, IOContext context) { @delegate.DeleteFile(name); } - catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception ioe) when (ioe.IsIOException()) { // this is fine: file may not exist } @@ -243,7 +243,7 @@ public override IndexOutput CreateOutput(string name, IOContext context) { cache.DeleteFile(name); } - catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception ioe) when (ioe.IsIOException()) { // this is fine: file may not exist } diff --git a/src/Lucene.Net/Store/NativeFSLockFactory.cs b/src/Lucene.Net/Store/NativeFSLockFactory.cs index b3c59a9f78..c02efb9065 100644 --- a/src/Lucene.Net/Store/NativeFSLockFactory.cs +++ b/src/Lucene.Net/Store/NativeFSLockFactory.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Support.IO; +using Lucene.Net.Support.IO; using Lucene.Net.Util; using System; using System.IO; @@ -289,12 +289,7 @@ public override bool Obtain() success = true; } - catch (IOException e) - { - FailureReason = e; - } - // LUCENENET: UnauthorizedAccessException does not derive from IOException like in java - catch (UnauthorizedAccessException e) + catch (Exception e) when (e.IsIOException()) { // At least on OS X, we will sometimes get an // intermittent "Permission Denied" Exception, @@ -396,7 +391,7 @@ public override bool IsLocked() } return !obtained; } - catch (IOException) + catch (Exception ioe) when (ioe.IsIOException()) { return false; } @@ -483,12 +478,7 @@ public override bool Obtain() { // no failure reason to be recorded, since this is the expected error if a lock exists } - catch (IOException e) - { - FailureReason = e; - } - // LUCENENET: UnauthorizedAccessException does not derive from IOException like in java - catch (UnauthorizedAccessException e) + catch (Exception e) when (e.IsIOException()) { // At least on OS X, we will sometimes get an // intermittent "Permission Denied" Exception, @@ -635,12 +625,7 @@ public override bool Obtain() { stream = GetLockFileStream(FileMode.OpenOrCreate); } - catch (IOException e) - { - FailureReason = e; - } - // LUCENENET: UnauthorizedAccessException does not derive from IOException like in java - catch (UnauthorizedAccessException e) + catch (Exception e) when (e.IsIOException()) { // At least on OS X, we will sometimes get an // intermittent "Permission Denied" Exception, diff --git a/src/Lucene.Net/Store/RAMDirectory.cs b/src/Lucene.Net/Store/RAMDirectory.cs index 446ed9dea9..f9daf8a900 100644 --- a/src/Lucene.Net/Store/RAMDirectory.cs +++ b/src/Lucene.Net/Store/RAMDirectory.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using J2N.Threading.Atomic; using System; using System.Collections.Concurrent; @@ -59,7 +59,7 @@ public RAMDirectory() { SetLockFactory(new SingleInstanceLockFactory()); } - catch (IOException) // LUCENENET: IDE0059: Remove unnecessary value assignment + catch (Exception e) when (e.IsIOException()) { // Cannot happen } diff --git a/src/Lucene.Net/Store/RAMInputStream.cs b/src/Lucene.Net/Store/RAMInputStream.cs index 3d72de06b1..e845d631b1 100644 --- a/src/Lucene.Net/Store/RAMInputStream.cs +++ b/src/Lucene.Net/Store/RAMInputStream.cs @@ -99,7 +99,7 @@ private void SwitchCurrentBuffer(bool enforceEOF) // end of file reached, no more buffers left if (enforceEOF) { - throw new EndOfStreamException("read past EOF: " + this); + throw EOFException.Create("read past EOF: " + this); } else { diff --git a/src/Lucene.Net/Store/SimpleFSDirectory.cs b/src/Lucene.Net/Store/SimpleFSDirectory.cs index 6f94a3a288..3ffb38fc04 100644 --- a/src/Lucene.Net/Store/SimpleFSDirectory.cs +++ b/src/Lucene.Net/Store/SimpleFSDirectory.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.IO; @@ -130,9 +130,9 @@ public override IndexInput OpenFullSlice() { return OpenSlice("full-slice", 0, descriptor.Length); } - catch (IOException ex) + catch (Exception ex) when (ex.IsIOException()) { - throw new Exception(ex.ToString(), ex); + throw RuntimeException.Create(ex); } } } @@ -213,7 +213,7 @@ protected override void ReadInternal(byte[] b, int offset, int len) if (position + len > m_end) { - throw new EndOfStreamException("read past EOF: " + this); + throw EOFException.Create("read past EOF: " + this); } try @@ -224,7 +224,7 @@ protected override void ReadInternal(byte[] b, int offset, int len) // int i = m_file.Read(b, offset + total, toRead); // if (i < 0) // be defensive here, even though we checked before hand, something could have changed // { - // throw new EndOfStreamException("read past EOF: " + this + " off: " + offset + " len: " + len + " total: " + total + " chunkLen: " + toRead + " end: " + m_end); + // throw EOFException.Create("read past EOF: " + this + " off: " + offset + " len: " + len + " total: " + total + " chunkLen: " + toRead + " end: " + m_end); // } // if (Debugging.AssertsEnabled) Debugging.Assert(i > 0, "RandomAccessFile.read with non zero-length toRead must always read at least one byte"); // total += i; @@ -237,7 +237,7 @@ protected override void ReadInternal(byte[] b, int offset, int len) if (Debugging.AssertsEnabled) Debugging.Assert(total == len); } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { throw new IOException(ioe.Message + ": " + this, ioe); } diff --git a/src/Lucene.Net/Store/VerifyingLockFactory.cs b/src/Lucene.Net/Store/VerifyingLockFactory.cs index 188352beea..bf9b71b888 100644 --- a/src/Lucene.Net/Store/VerifyingLockFactory.cs +++ b/src/Lucene.Net/Store/VerifyingLockFactory.cs @@ -56,7 +56,7 @@ private void Verify(byte message) int ret = outerInstance.stream.ReadByte(); if (ret < 0) { - throw new InvalidOperationException("Lock server died because of locking error."); + throw IllegalStateException.Create("Lock server died because of locking error."); } if (ret != message) { diff --git a/src/Lucene.Net/Support/BitArrayExtensions.cs b/src/Lucene.Net/Support/BitArrayExtensions.cs index 353556dd74..31a78591a2 100644 --- a/src/Lucene.Net/Support/BitArrayExtensions.cs +++ b/src/Lucene.Net/Support/BitArrayExtensions.cs @@ -1,4 +1,4 @@ -/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -149,7 +149,7 @@ public static int NextClearBit(this BitArray bitArray, int index) /// The number of bits set to true in this . public static int Cardinality(this BitArray bits) { - if (bits == null) + if (bits is null) throw new ArgumentNullException(nameof(bits)); int count = 0; diff --git a/src/Lucene.Net/Support/Codecs/DefaultCodecFactory.cs b/src/Lucene.Net/Support/Codecs/DefaultCodecFactory.cs index 589a9055b6..c4e74a0cb9 100644 --- a/src/Lucene.Net/Support/Codecs/DefaultCodecFactory.cs +++ b/src/Lucene.Net/Support/Codecs/DefaultCodecFactory.cs @@ -207,7 +207,7 @@ protected virtual void ScanForCodecs(Assembly assembly) /// A type that subclasses . protected virtual void PutCodecType(Type codec) { - if (codec == null) + if (codec is null) throw new ArgumentNullException(nameof(codec)); if (!typeof(Codec).IsAssignableFrom(codec)) throw new ArgumentException($"The supplied type {codec.AssemblyQualifiedName} does not subclass {nameof(Codec)}."); @@ -246,7 +246,7 @@ public virtual Codec GetCodec(string name) /// The instance. protected virtual Codec GetCodec(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); if (!codecInstanceCache.TryGetValue(type, out Codec instance)) { @@ -280,7 +280,7 @@ protected virtual Codec NewCodec(Type type) /// The . protected virtual Type GetCodecType(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); EnsureInitialized(); if (!codecNameToTypeMap.TryGetValue(name, out Type codecType) || codecType == null) diff --git a/src/Lucene.Net/Support/Codecs/DefaultDocValuesFormatFactory.cs b/src/Lucene.Net/Support/Codecs/DefaultDocValuesFormatFactory.cs index 3c70b1e88d..e7e1b4f6bb 100644 --- a/src/Lucene.Net/Support/Codecs/DefaultDocValuesFormatFactory.cs +++ b/src/Lucene.Net/Support/Codecs/DefaultDocValuesFormatFactory.cs @@ -203,7 +203,7 @@ protected virtual void ScanForDocValuesFormats(Assembly assembly) /// A type that subclasses . protected virtual void PutDocValuesFormatType(Type docValuesFormat) { - if (docValuesFormat == null) + if (docValuesFormat is null) throw new ArgumentNullException(nameof(docValuesFormat)); if (!typeof(DocValuesFormat).IsAssignableFrom(docValuesFormat)) throw new ArgumentException($"The supplied type {docValuesFormat.AssemblyQualifiedName} does not subclass {nameof(DocValuesFormat)}."); @@ -242,7 +242,7 @@ public virtual DocValuesFormat GetDocValuesFormat(string name) /// The instance. protected virtual DocValuesFormat GetDocValuesFormat(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); if (!docValuesFormatInstanceCache.TryGetValue(type, out DocValuesFormat instance)) { @@ -276,7 +276,7 @@ protected virtual DocValuesFormat NewDocValuesFormat(Type type) /// The . protected virtual Type GetDocValuesFormatType(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); EnsureInitialized(); if (!docValuesFormatNameToTypeMap.TryGetValue(name, out Type codecType) || codecType == null) diff --git a/src/Lucene.Net/Support/Codecs/DefaultPostingsFormatFactory.cs b/src/Lucene.Net/Support/Codecs/DefaultPostingsFormatFactory.cs index cea2c374d1..8da5aebc1c 100644 --- a/src/Lucene.Net/Support/Codecs/DefaultPostingsFormatFactory.cs +++ b/src/Lucene.Net/Support/Codecs/DefaultPostingsFormatFactory.cs @@ -203,7 +203,7 @@ protected virtual void ScanForPostingsFormats(Assembly assembly) /// A type that subclasses . protected virtual void PutPostingsFormatType(Type postingsFormat) { - if (postingsFormat == null) + if (postingsFormat is null) throw new ArgumentNullException(nameof(postingsFormat)); if (!typeof(PostingsFormat).IsAssignableFrom(postingsFormat)) throw new ArgumentException($"The supplied type {postingsFormat.AssemblyQualifiedName} does not subclass {nameof(PostingsFormat)}."); @@ -242,7 +242,7 @@ public virtual PostingsFormat GetPostingsFormat(string name) /// The instance. protected virtual PostingsFormat GetPostingsFormat(Type type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); if (!postingsFormatInstanceCache.TryGetValue(type, out PostingsFormat instance)) { @@ -276,7 +276,7 @@ protected virtual PostingsFormat NewPostingsFormat(Type type) /// The . protected virtual Type GetPostingsFormatType(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); EnsureInitialized(); if (!postingsFormatNameToTypeMap.TryGetValue(name, out Type codecType) || codecType == null) diff --git a/src/Lucene.Net/Support/ConcurrentHashSet.cs b/src/Lucene.Net/Support/ConcurrentHashSet.cs index 60a18d681a..c728b3961d 100644 --- a/src/Lucene.Net/Support/ConcurrentHashSet.cs +++ b/src/Lucene.Net/Support/ConcurrentHashSet.cs @@ -196,7 +196,7 @@ public ConcurrentHashSet(IEqualityComparer comparer) public ConcurrentHashSet(IEnumerable collection, IEqualityComparer comparer) : this(comparer) { - if (collection == null) throw new ArgumentNullException(nameof(collection)); + if (collection is null) throw new ArgumentNullException(nameof(collection)); InitializeFromCollection(collection); } @@ -223,7 +223,7 @@ public ConcurrentHashSet(IEnumerable collection, IEqualityComparer compare public ConcurrentHashSet(int concurrencyLevel, IEnumerable collection, IEqualityComparer comparer) : this(concurrencyLevel, DefaultCapacity, false, comparer) { - if (collection == null) throw new ArgumentNullException(nameof(collection)); + if (collection is null) throw new ArgumentNullException(nameof(collection)); InitializeFromCollection(collection); } @@ -422,7 +422,7 @@ public IEnumerator GetEnumerator() void ICollection.CopyTo(T[] array, int arrayIndex) { - if (array == null) throw new ArgumentNullException(nameof(array)); + if (array is null) throw new ArgumentNullException(nameof(array)); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); var locksAcquired = 0; @@ -791,7 +791,7 @@ public void SymmetricExceptWith(IEnumerable other) public void UnionWith(IEnumerable other) { - if (other == null) + if (other is null) throw new ArgumentNullException(nameof(other)); var locksAcquired = 0; diff --git a/src/Lucene.Net/Support/ConcurrentSet.cs b/src/Lucene.Net/Support/ConcurrentSet.cs index 103220fda1..56198010fd 100644 --- a/src/Lucene.Net/Support/ConcurrentSet.cs +++ b/src/Lucene.Net/Support/ConcurrentSet.cs @@ -132,7 +132,7 @@ public void CopyTo(T[] array, int arrayIndex) void ICollection.CopyTo(Array array, int index) { - if (array == null) + if (array is null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException("Only single dimensional arrays are supported for the requested action.", nameof(array)); @@ -159,7 +159,7 @@ void ICollection.CopyTo(Array array, int index) #pragma warning disable IDE0019 // Use pattern matching object?[]? objects = array as object[]; #pragma warning restore IDE0019 // Use pattern matching - if (objects == null) + if (objects is null) { throw new ArgumentException("Target array type is not compatible with the type of items in the collection.", nameof(array)); //throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); diff --git a/src/Lucene.Net/Support/Diagnostics/AssertionException.cs b/src/Lucene.Net/Support/Diagnostics/AssertionException.cs index e6e627f1c5..9553d576b9 100644 --- a/src/Lucene.Net/Support/Diagnostics/AssertionException.cs +++ b/src/Lucene.Net/Support/Diagnostics/AssertionException.cs @@ -30,7 +30,7 @@ namespace Lucene.Net.Diagnostics #if FEATURE_SERIALIZABLE_EXCEPTIONS [Serializable] #endif - public class AssertionException : Exception + public class AssertionException : Exception, IError { /// /// Constructs an with no detail message. diff --git a/src/Lucene.Net/Support/Diagnostics/Debugging.cs b/src/Lucene.Net/Support/Diagnostics/Debugging.cs index 0dca2f034a..cb7b6e65a9 100644 --- a/src/Lucene.Net/Support/Diagnostics/Debugging.cs +++ b/src/Lucene.Net/Support/Diagnostics/Debugging.cs @@ -1,6 +1,7 @@ -using J2N.Text; +using J2N.Text; using Lucene.Net.Util; using System; +using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lucene.Net.Diagnostics @@ -43,6 +44,7 @@ internal static class Debugging /// IMPORTANT: For best performance, only call this method after checking to ensure the value of is true. /// /// The conditional expression to evaluate. If the condition is true, no exception is thrown. + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition) { @@ -66,6 +68,7 @@ public static void Assert(bool condition) /// This message contains text intermixed with zero or more format items, which correspond to /// the parameter. /// The parameter corresponding to the format item at index 0 ({0}). + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition, string messageFormat, T0 p0) { @@ -90,6 +93,7 @@ public static void Assert(bool condition, string messageFormat, T0 p0) /// the or parameters. /// The parameter corresponding to the format item at index 0 ({0}). /// The parameter corresponding to the format item at index 1 ({1}). + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition, string messageFormat, T0 p0, T1 p1) { @@ -115,6 +119,7 @@ public static void Assert(bool condition, string messageFormat, T0 p0, T /// The parameter corresponding to the format item at index 0 ({0}). /// The parameter corresponding to the format item at index 1 ({1}). /// The parameter corresponding to the format item at index 2 ({2}). + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition, string messageFormat, T0 p0, T1 p1, T2 p2) { @@ -141,6 +146,7 @@ public static void Assert(bool condition, string messageFormat, T0 p /// The parameter corresponding to the format item at index 1 ({1}). /// The parameter corresponding to the format item at index 2 ({2}). /// The parameter corresponding to the format item at index 3 ({3}). + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition, string messageFormat, T0 p0, T1 p1, T2 p2, T3 p3) { @@ -169,6 +175,7 @@ public static void Assert(bool condition, string messageFormat, /// The parameter corresponding to the format item at index 2 ({2}). /// The parameter corresponding to the format item at index 3 ({3}). /// The parameter corresponding to the format item at index 4 ({4}). + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition, string messageFormat, T0 p0, T1 p1, T2 p2, T3 p3, T4 p4) { @@ -198,6 +205,7 @@ public static void Assert(bool condition, string messageForm /// The parameter corresponding to the format item at index 3 ({3}). /// The parameter corresponding to the format item at index 4 ({4}). /// The parameter corresponding to the format item at index 5 ({5}). + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition, string messageFormat, T0 p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5) { @@ -228,6 +236,7 @@ public static void Assert(bool condition, string message /// The parameter corresponding to the format item at index 4 ({4}). /// The parameter corresponding to the format item at index 5 ({5}). /// The parameter corresponding to the format item at index 6 ({6}). + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition, string messageFormat, T0 p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6) { @@ -259,6 +268,7 @@ public static void Assert(bool condition, string mes /// The parameter corresponding to the format item at index 5 ({5}). /// The parameter corresponding to the format item at index 6 ({6}). /// The parameter corresponding to the format item at index 7 ({7}). + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition, string messageFormat, T0 p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7) { @@ -276,6 +286,7 @@ public static void Assert(bool condition, string /// /// The conditional expression to evaluate. If the condition is true, no exception is thrown. /// The message to use to indicate a failure of . + [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert(bool condition, string message) { @@ -287,7 +298,7 @@ public static void Assert(bool condition, string message) ///// Checks for a condition; if the condition is false, throws an . ///// ///// A delegate that returns the conditional expression to evaluate. If the condition is true, no exception is thrown. - + //[DebuggerStepThrough] //[MethodImpl(MethodImplOptions.AggressiveInlining)] //public static void Assert(Func conditionFactory) //{ @@ -302,6 +313,7 @@ public static void Assert(bool condition, string message) ///// ///// A delegate that returns the conditional expression to evaluate. If the condition returned from the factory is true, no exception is thrown. ///// A delegate to build the message to use. + //[DebuggerStepThrough] //[MethodImpl(MethodImplOptions.AggressiveInlining)] //public static void Assert(Func conditionFactory, Func messageFactory) //{ diff --git a/src/Lucene.Net/Support/DictionaryExtensions.cs b/src/Lucene.Net/Support/DictionaryExtensions.cs index 8b22c1fa6e..7238137404 100644 --- a/src/Lucene.Net/Support/DictionaryExtensions.cs +++ b/src/Lucene.Net/Support/DictionaryExtensions.cs @@ -24,7 +24,7 @@ internal static class DictionaryExtensions { public static void PutAll(this IDictionary dict, IEnumerable> kvps) { - if (dict == null) + if (dict is null) throw new ArgumentNullException(nameof(dict)); foreach (var kvp in kvps) @@ -35,7 +35,7 @@ public static void PutAll(this IDictionary dict, IEn public static TValue Put(this IDictionary dict, TKey key, TValue value) { - if (dict == null) + if (dict is null) throw new ArgumentNullException(nameof(dict)); if (!dict.TryGetValue(key, out TValue oldValue)) diff --git a/src/Lucene.Net/Support/EnumerableExtensions.cs b/src/Lucene.Net/Support/EnumerableExtensions.cs index d978aa277d..4f9bde706f 100644 --- a/src/Lucene.Net/Support/EnumerableExtensions.cs +++ b/src/Lucene.Net/Support/EnumerableExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace Lucene.Net.Support @@ -40,9 +40,9 @@ internal static class EnumerableExtensions /// A new containing the results from each pair. public static IEnumerable InPairs(this IEnumerable source, Func join) { - if (source == null) + if (source is null) throw new ArgumentNullException(nameof(source)); - if (join == null) + if (join is null) throw new ArgumentNullException(nameof(join)); using IEnumerator enumerator = source.GetEnumerator(); @@ -66,7 +66,7 @@ public static IEnumerable InPairs(this IEnumerable source, Fun /// The resulting . public static IEnumerable TakeAllButLast(this IEnumerable source) { - if (source == null) + if (source is null) throw new ArgumentNullException(nameof(source)); return TakeAllButLastImpl(source); @@ -96,7 +96,7 @@ private static IEnumerable TakeAllButLastImpl(IEnumerable source) /// The resulting . public static IEnumerable TakeAllButLast(this IEnumerable source, int n) { - if (source == null) + if (source is null) throw new ArgumentNullException(nameof(source)); if (n < 0) diff --git a/src/Lucene.Net/Support/ExceptionHandling/Errors/AssertionError.cs b/src/Lucene.Net/Support/ExceptionHandling/Errors/AssertionError.cs new file mode 100644 index 0000000000..ef2f6b3d96 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Errors/AssertionError.cs @@ -0,0 +1,90 @@ +using Lucene.Net.Diagnostics; +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown to indicate that an assertion has failed. + /// + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsAssertionError()) + /// + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class AssertionError : AssertionException + { + [Obsolete("Use AssertionError.Create() instead.", error: true)] + public AssertionError() + { + } + + [Obsolete("Use AssertionError.Create() instead.", error: true)] + public AssertionError(string message) : base(message) + { + } + + [Obsolete("Use AssertionError.Create() instead.", error: true)] + public AssertionError(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use AssertionError.Create() instead.", error: true)] + public AssertionError(Exception cause) : base(cause?.ToString(), cause) + { + } + + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected AssertionError(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new AssertionException(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new AssertionException(message); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new AssertionException(message, innerException); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new AssertionException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Errors/Error.cs b/src/Lucene.Net/Support/ExceptionHandling/Errors/Error.cs new file mode 100644 index 0000000000..6ef4082111 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Errors/Error.cs @@ -0,0 +1,100 @@ +using Lucene.Net.Diagnostics; +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// The Java Error type to simulate the type in Java that all Errors inherit. + /// + /// NOTE: Exception and Error in Java have the same base type, Throwable. However, + /// that is the only common type so Exceptions can be caught without catching errors. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsError()) + /// + /// + /// Error can be thrown, but cannot be subclassed in C# because it is internal. + /// For all Lucene exceptions that subclass Error, implement the + /// interface, then choose the most logical exception type in .NET to subclass. + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class Error : Exception, IError + { + [Obsolete("Use Error.Create() instead.", error: true)] + public Error() + { + } + + [Obsolete("Use Error.Create() instead.", error: true)] + public Error(string message) : base(message) + { + } + + [Obsolete("Use Error.Create() instead.", error: true)] + public Error(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use Error.Create() instead.", error: true)] + public Error(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected Error(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + // LUCENENET: For now, we are just using AssertionException because it is our only public error type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new AssertionException(); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new AssertionException(message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new AssertionException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new AssertionException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Errors/IError.cs b/src/Lucene.Net/Support/ExceptionHandling/Errors/IError.cs new file mode 100644 index 0000000000..c375b1b1d4 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Errors/IError.cs @@ -0,0 +1,32 @@ +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Used to identify an exception as a Java Error type. + /// + /// Lucene Exception types need to be identified as an Error to our exception + /// handling framework when they derive from Error in Java. + /// However, is internal and C# doesn't allow a + /// public exception to subclass an internal one, so as a workaround, + /// add this interface instead and subclass the most logical exception in .NET. + /// + internal interface IError + { + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Errors/NoClassDefFoundError.cs b/src/Lucene.Net/Support/ExceptionHandling/Errors/NoClassDefFoundError.cs new file mode 100644 index 0000000000..196f639a48 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Errors/NoClassDefFoundError.cs @@ -0,0 +1,91 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of + /// a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. + /// + /// The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsNoClassDefFoundError()) + /// + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class NoClassDefFoundError : Exception, IError // LUCENENET: Subclassing Error is not allowed, so we identify with the IError interface and subclass Exception + { + [Obsolete("Use NoClassDefFoundError.Create() instead.", error: true)] + public NoClassDefFoundError() + { + } + + [Obsolete("Use NoClassDefFoundError.Create() instead.", error: true)] + public NoClassDefFoundError(string message) : base(message) + { + } + + [Obsolete("Use NoClassDefFoundError.Create() instead.", error: true)] + public NoClassDefFoundError(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use NoClassDefFoundError.Create() instead.", error: true)] + public NoClassDefFoundError(Exception cause) : base(cause?.ToString(), cause) + { + } + + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected NoClassDefFoundError(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new TypeLoadException(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new TypeLoadException(message); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new TypeLoadException(message, innerException); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new TypeLoadException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Errors/OutOfMemoryError.cs b/src/Lucene.Net/Support/ExceptionHandling/Errors/OutOfMemoryError.cs new file mode 100644 index 0000000000..d9f22ab2b2 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Errors/OutOfMemoryError.cs @@ -0,0 +1,92 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown when the Java Virtual Machine cannot allocate an object because + /// it is out of memory, and no more memory could be made available by the + /// garbage collector. OutOfMemoryError objects may be constructed by the virtual + /// machine as if + /// suppression were disabled and/or the stack trace was not writable. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsOutOfMemoryError()) + /// + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class OutOfMemoryError : OutOfMemoryException, IError + { + [Obsolete("Use OutOfMemoryError.Create() instead.", error: true)] + public OutOfMemoryError() + { + } + + [Obsolete("Use OutOfMemoryError.Create() instead.", error: true)] + public OutOfMemoryError(string message) : base(message) + { + } + + [Obsolete("Use OutOfMemoryError.Create() instead.", error: true)] + public OutOfMemoryError(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use OutOfMemoryError.Create() instead.", error: true)] + public OutOfMemoryError(Exception cause) : base(cause?.ToString(), cause) + { + } + + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected OutOfMemoryError(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new OutOfMemoryException(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new OutOfMemoryException(message); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new OutOfMemoryException(message, innerException); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new OutOfMemoryException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Errors/ServiceConfigurationError.cs b/src/Lucene.Net/Support/ExceptionHandling/Errors/ServiceConfigurationError.cs new file mode 100644 index 0000000000..a1a4fab701 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Errors/ServiceConfigurationError.cs @@ -0,0 +1,128 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Error thrown when something goes wrong while loading a service provider. + /// + /// This error will be thrown in the following situations: + /// + /// The format of a provider-configuration file violates the specification; + /// An occurs while reading a provider-configuration file; + /// A concrete provider class named in a provider-configuration file cannot be found; + /// A concrete provider class is not a subclass of the service class; + /// A concrete provider class cannot be instantiated; or + /// Some other kind of error occurs. + /// + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsServiceConfigurationError()) + /// + /// + /// Error can be thrown, but cannot be subclassed in C# because it is internal. + /// For all Lucene exceptions that subclass Error, implement the + /// interface, then choose the most logical exception type in .NET to subclass. + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class ServiceConfigurationError : InvalidOperationException, IError + { + [Obsolete("Use ServiceConfigurationError.Create() instead.", error: true)] + public ServiceConfigurationError() + { + } + + [Obsolete("Use ServiceConfigurationError.Create() instead.", error: true)] + public ServiceConfigurationError(string message) : base(message) + { + } + + [Obsolete("Use ServiceConfigurationError.Create() instead.", error: true)] + public ServiceConfigurationError(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use ServiceConfigurationError.Create() instead.", error: true)] + public ServiceConfigurationError(Exception cause) + : base(cause?.ToString(), cause) + { + } + + private ServiceConfigurationError(bool privateOverload) + { + } + + private ServiceConfigurationError(string message, bool privateOverload) : base(message) + { + } + + private ServiceConfigurationError(string message, Exception innerException, bool privateOverload) : base(message, innerException) + { + } + + private ServiceConfigurationError(Exception cause, bool privateOverload) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected ServiceConfigurationError(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + // LUCENENET: Since this exception is only thrown in AnalysisSPILoader, we are simply throwing the internal type. + // Users can catch it as InvalidOperationException. + // Since it is possible that AnalysisSPILoader will someday be factored out in favor of true dependency injection, + // it is not sensible to make a public exception that will be factored out along with it. + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new ServiceConfigurationError(privateOverload: true); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new ServiceConfigurationError(message, privateOverload: true); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new ServiceConfigurationError(message, innerException, privateOverload: true); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new ServiceConfigurationError(cause.Message, cause, privateOverload: true); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Errors/StackOverflowError.cs b/src/Lucene.Net/Support/ExceptionHandling/Errors/StackOverflowError.cs new file mode 100644 index 0000000000..171b4329b4 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Errors/StackOverflowError.cs @@ -0,0 +1,88 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown when a stack overflow occurs because an application recurses too deeply. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsStackOverflowError()) + /// + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class StackOverflowError : Exception, IError // LUCENENET: StackOverflowException is sealed, so we subclass Exception instead and use IError to identify to Lucene.NET as an error + { + [Obsolete("Use NoClassDefFoundError.Create() instead.", error: true)] + public StackOverflowError() + { + } + + [Obsolete("Use NoClassDefFoundError.Create() instead.", error: true)] + public StackOverflowError(string message) : base(message) + { + } + + [Obsolete("Use NoClassDefFoundError.Create() instead.", error: true)] + public StackOverflowError(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use NoClassDefFoundError.Create() instead.", error: true)] + public StackOverflowError(Exception cause) : base(cause?.ToString(), cause) + { + } + + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected StackOverflowError(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new StackOverflowException(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new StackOverflowException(message); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new StackOverflowException(message, innerException); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new StackOverflowException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/ExceptionExtensions.cs b/src/Lucene.Net/Support/ExceptionHandling/ExceptionExtensions.cs new file mode 100644 index 0000000000..eef397c214 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/ExceptionExtensions.cs @@ -0,0 +1,691 @@ +using J2N.Text; +using Lucene.Net.Diagnostics; +using System; +using System.IO; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Security; +using System.Threading; + +namespace Lucene +{ + /* + * 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. + /// + internal static class ExceptionExtensions + { + internal static Type NUnitResultStateExceptionType = null; // All NUnit public exceptions derive from this base class + internal static Type NUnitAssertionExceptionType = null; + internal static Type NUnitMultipleAssertExceptionType = null; + internal static Type NUnitInconclusiveExceptionType = null; + internal static Type NUnitSuccessExceptionType = null; // Since this doesn't correspond to anything in Java, we should always ignore it + internal static Type NUnitInvalidPlatformException = null; // Internal exception that subclasses ArgumentException that probably isn't thrown outside of NUnit, but if it ever is we should ignore it always + internal static Type DebugAssertExceptionType = null; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool IsAlwaysIgnored(this Exception e) + { + return (!(NUnitSuccessExceptionType is null) && NUnitSuccessExceptionType.IsAssignableFrom(e.GetType())) || + (!(NUnitInvalidPlatformException is null) && NUnitInvalidPlatformException.IsAssignableFrom(e.GetType())); + } + + /// + /// Used to check whether corresponds to a Throwable + /// in Java. Throwable is the base class for all errors in Java. + /// + /// Unused, all errors in Java are throwble. + /// Always returns true. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsThrowable(this Exception e) + { + if (e is null || e.IsAlwaysIgnored()) return false; + + return true; + } + + /// + /// Used to check whether corresponds to an AssertionError + /// in Java. Error indicates serious problems that a reasonable application + /// should not try to catch. + /// + /// This exception. + /// true if corresponds to an AssertionError type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsAssertionError(this Exception e) + { + if (e is null || e.IsAlwaysIgnored()) return false; + + return e is AssertionException || + (!(DebugAssertExceptionType is null) && DebugAssertExceptionType.IsAssignableFrom(e.GetType())) || + // Ignore NUnit exceptions (in tests) + (!(NUnitAssertionExceptionType is null) && NUnitAssertionExceptionType.IsAssignableFrom(e.GetType())) || + (!(NUnitMultipleAssertExceptionType is null) && NUnitMultipleAssertExceptionType.IsAssignableFrom(e.GetType())); + } + + /// + /// Used to check whether corresponds to an Error + /// in Java. Error indicates serious problems that a reasonable application + /// should not try to catch. + /// + /// This exception. + /// true if corresponds to an Error type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsError(this Exception e) + { + if (e is null || e.IsAlwaysIgnored() || + // Exclude InconclusiveException - AssumptionViolatedException derives from RuntimeException in Java so it is not an Error type + (!(NUnitInconclusiveExceptionType is null) && NUnitInconclusiveExceptionType.IsAssignableFrom(e.GetType())) + ) return false; + + return + e is IError || + e is OutOfMemoryException || + e is AssertionException || + // e.IsNoClassDefFoundError() || // NOTE: These are technically errors, but they overlap other exception types in .NET. Since Lucene always catches this at the source, we can ignore here. + e is StackOverflowException || // Not catchable in .NET unless we throw it, but mainly here just for documentation purposes + // Ignore .NET debug assert statements (only valid when test framework is attached) + (!(DebugAssertExceptionType is null) && DebugAssertExceptionType.IsAssignableFrom(e.GetType())) || + // Ignore NUnit exceptions (in tests) + (!(NUnitResultStateExceptionType is null) && NUnitResultStateExceptionType.IsAssignableFrom(e.GetType())); + } + + /// + /// Used to check whether corresponds to an Exception + /// in Java. RuntimeException in Java indicates conditions that a reasonable application + /// might want to catch. + /// + /// WARNING: Error in Java doesn't inherit from Exception, so it is important to use + /// this method in a catch block. Instead of catch (Exception e), use + /// catch (Exception e) when (e.IsException()). + /// + /// This exception. + /// true if corresponds to an Exception type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsException(this Exception e) + { + if (e is null || e.IsAlwaysIgnored()) return false; + + return e is Exception && !IsError(e); // IMPORTANT: Error types should not be identified here. + } + + /// + /// Used to check whether corresponds to a RuntimeException + /// in Java. RuntimeException in Java indicates an unchecked exception. Unchecked + /// exceptions don't force the developer to make a decision whether to handle or re-throw + /// the excption, it can safely be ignored and allowed to propagate. + /// + /// This exception. + /// true if corresponds to a RuntimeException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsRuntimeException(this Exception e) + { + if (e is null || + + e.IsAlwaysIgnored() || + + // Some Java errors derive from SystemException in .NET, but we don't want to include them here + e.IsError() || + + // .NET made IOException a SystemExcpetion, but those should not be included here + e.IsIOException() || + + // ObjectDisposedException is a special case because in Lucene the AlreadyClosedException derived + // from IOException and was therefore a checked excpetion type. + e is ObjectDisposedException || + + // These seem to correspond closely to java.lang.ReflectiveOperationException, which are not derived from RuntimeException + e is MemberAccessException || + e is ReflectionTypeLoadException || + e is AmbiguousMatchException + ) + { + return false; + } + + // Known implemetnations of IRuntimeException + + // LuceneExcpetion + // BytesRefHash.MaxBytesLengthExceededException + // CollectionTerminatedException + // TimeLimitingCollector.TimeExceededException + // BooleanQuery.TooManyClausesException + return e is IRuntimeException || + + // LUCENENET NOTE: There may be some other types to exclude here, but this is pretty similar to what Java is doing + // once you weed out the above exclusions. This handler is only used in a few places (mostly tests to check exception handling) + // so it is not likely it matters beyond this point. + + // See the tests to see the list of exception types that are expected to be caught here + e is SystemException || + + e is J2N.IO.BufferUnderflowException || + e is J2N.IO.BufferOverflowException || + e is J2N.IO.InvalidMarkException || + + (NUnitInconclusiveExceptionType is null ? false : NUnitInconclusiveExceptionType.IsAssignableFrom(e.GetType())); + } + + /// + /// Used to check whether corresponds to an IOException + /// in Java. + /// + /// WARNING: java.nio.file.AccessDeniedException inherits from IOException, + /// its .NET counterpart does not. Therefore, is important to use + /// this method in a catch block to ensure there are no gaps. Instead of catch (IOException e), use + /// catch (Exception e) when (e.IsIOException()). + /// + /// This exception. + /// true if corresponds to an IOException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsIOException(this Exception e) + { + if (e is null || e.IsAlwaysIgnored()) return false; + + return e is IOException || + e.IsAlreadyClosedException() || // In Lucene, AlreadyClosedException subclass IOException instead of InvalidOperationException, so we need a special case here + e is UnauthorizedAccessException; // In Java, java.nio.file.AccessDeniedException subclasses IOException + } + + /// + /// Used to check whether corresponds to an ArrayIndexOutOfBoundsException + /// in Java. + /// + /// This exception. + /// true if corresponds to an ArrayIndexOutOfBoundsException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsArrayIndexOutOfBoundsException(this Exception e) + { + if (e is null || e.IsAlwaysIgnored()) return false; + + return e is ArgumentOutOfRangeException || + e is IndexOutOfRangeException; + } + + /// + /// Used to check whether corresponds to a StringIndexOutOfBoundsException + /// in Java. + /// + /// This exception. + /// true if corresponds to a StringIndexOutOfBoundsException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsStringIndexOutOfBoundsException(this Exception e) + { + if (e is null || e.IsAlwaysIgnored()) return false; + + return e is ArgumentOutOfRangeException || + e is IndexOutOfRangeException; + } + + /// + /// Used to check whether corresponds to an IndexOutOfBoundsException + /// in Java. + /// + /// This exception. + /// true if corresponds to an IndexOutOfBoundsException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsIndexOutOfBoundsException(this Exception e) + { + if (e is null || e.IsAlwaysIgnored()) return false; + + return e is ArgumentOutOfRangeException || + e is IndexOutOfRangeException; + } + + /// + /// Used to check whether corresponds to a NoSuchFileException + /// or a FileNotFoundExcpetion in Java. + /// + /// NOTE: In Java, there is no distinction between file and directory, and FileNotFoundException is thrown + /// in either case. Therefore, this handler also catches . + /// + /// This exception. + /// true if corresponds to a NoSuchFileException or a FileNotFoundException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNoSuchFileExceptionOrFileNotFoundException(this Exception e) + { + return e is FileNotFoundException || + // Java doesn't have an equivalent to DirectoryNotFoundExcption, but + // Lucene added one that subclassed java.io.FileNotFoundException + // that we didn't add to the .NET port. + e is DirectoryNotFoundException; + } + + /// + /// Used to check whether corresponds to a ParseException + /// in Java. + /// + /// IMPORTANT: QueryParser has its own ParseException types (there are multiple), + /// so be sure not to use this exception instead of the ones in QueryParser. + /// For QueryParser exceptions, there are no extension methods to use for identification + /// in catch blocks, you should instead use the fully-qualified name of the exception. + /// + /// catch (Lucene.Net.QueryParsers.Surround.Parser.ParseException e) + /// + /// + /// This exception. + /// true if corresponds to a ParseException type + /// in Java; otherwise false. + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsParseException(this Exception e) + { + // LUCENNET: Added this exception in J2N to cover this case because it is not a RuntimeException + // which makes it different from NumberFormatException in Java and FormatException in .NET. + return e is ParseException; + } + + /// + /// Used to check whether corresponds to a NumberFormatException + /// in Java. + /// + /// This exception. + /// true if corresponds to an NumberFormatException type + /// in Java; otherwise false. + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNumberFormatException(this Exception e) + { + return e is FormatException; + } + + /// + /// Used to check whether corresponds to an InvocationTargetException + /// in Java. + /// + /// This exception. + /// true if corresponds to an InvocationTargetException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsInvocationTargetException(this Exception e) + { + return e is TargetInvocationException; + } + + /// + /// Used to check whether corresponds to an IllegalAccessException + /// in Java. + /// + /// This exception. + /// true if corresponds to an IllegalAccessException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsIllegalAccessException(this Exception e) + { + return e is MemberAccessException || + e is TypeAccessException; + } + + /// + /// Used to check whether corresponds to an IllegalArgumentException + /// in Java. + /// + /// 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; + + // LUCENENET: In production, there is a chance that we will upgrade to ArgumentNullExcpetion or ArgumentOutOfRangeException + // and it is still important that those are caught. However, we have a copy of this method in the test environment + // where this is done more strictly to catch ArgumentException without its known subclasses so we can be more explicit in tests. + 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. + } + + /// + /// Used to check whether corresponds to a NullPointerException + /// in Java. + /// + /// This exception. + /// true if corresponds to a NullPointerException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNullPointerException(this Exception e) + { + if (e is null || e.IsAlwaysIgnored()) return false; + + return e is ArgumentNullException || + e is NullReferenceException; // LUCENENET TODO: These could be real problems where excptions can be prevevented that our catch blocks are hiding + } + + /// + /// Used to check whether corresponds to an InstantiationException + /// (Reflection) in Java. + /// + /// NOTE: The current implementation is intended to work with and its overloads, + /// so if InstantiationException is used in contexts in Java other than <class>.newInstance() + /// or Constructor.newInstance(), it may require research. + /// + /// This exception. + /// true if corresponds to an InstantiationException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsInstantiationException(this Exception e) + { + // LUCENENET NOTE: This is just a best guess, being that these are the "variety of reasons" + // described in the javadoc that the class might not be created when using Activator.CreateInstance(). + // The TestFactories class also seems to rule out that this is supposed to catch TargetInvocationException + // or security exceptions such as MemberAccessException or TypeAccessException. + return e is MissingMethodException || + e is TypeLoadException || + e is ReflectionTypeLoadException || + e is TypeInitializationException; // May happen due to a class initializer that throws an uncaught exception. + } + + /// + /// Used to check whether corresponds to an UnsupportedOperationException + /// in Java. + /// + /// This exception. + /// true if corresponds to an UnsupportedOperationException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsUnsupportedOperationException(this Exception e) + { + return e is NotSupportedException; + } + + /// + /// Used to check whether corresponds to an UnsupportedEncodingException + /// in Java. + /// + /// This exception. + /// true if corresponds to an UnsupportedEncodingException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsUnsupportedEncodingException(this Exception e) + { + // According to the docs, this maps to 2 potential exceptions: + // https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.getencoding?view=net-5.0 + return e is ArgumentException || + e is PlatformNotSupportedException; + } + + /// + /// Used to check whether corresponds to an InterruptedException + /// in Java. + /// + /// This exception. + /// true if corresponds to an InterruptedException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsInterruptedException(this Exception e) + { + // LUCENENET: Special case - we only catch under certain scenarios and do not rethrow explicitly. + // This exception is the shutdown signal for a thread and it is used in Lucene for control flow. + // However, in .NET it is thrown in more cases than in Java. So, rather than wrapping it in a new + // exception type, we don't catch it unless there is a specific reason to do something other than re-throw. + return e is ThreadInterruptedException; + } + + /// + /// Used to check whether corresponds to a CompressorException + /// in Java. + /// + /// This exception. + /// true if corresponds to a CompressorException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsCompressorException(this Exception e) + { + return e is InvalidDataException; // LUCENENET TODO: Not sure if this is the right exception + } + + /// + /// Used to check whether corresponds to a DataFormatException + /// in Java. + /// + /// This exception. + /// true if corresponds to a DataFormatException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsDataFormatException(this Exception e) + { + return e is InvalidDataException; + } + + /// + /// Used to check whether corresponds to a SecurityException + /// in Java. + /// + /// This exception. + /// true if corresponds to a SecurityException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsSecurityException(this Exception e) + { + return e is SecurityException; + } + + /// + /// Used to check whether corresponds to a NoSuchDirectoryException + /// in Java. + /// + /// This exception. + /// true if corresponds to a NoSuchDirectoryException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNoSuchDirectoryException(this Exception e) + { + return e is DirectoryNotFoundException; + } + + /// + /// Used to check whether corresponds to an OutOfMemoryError + /// in Java. + /// + /// This exception. + /// true if corresponds to an OutOfMemoryError type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsOutOfMemoryError(this Exception e) + { + return e is OutOfMemoryException; + } + + /// + /// Used to check whether corresponds to an AlreadyClosedException + /// in Java. + /// + /// This exception. + /// true if corresponds to an AlreadyClosedException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsAlreadyClosedException(this Exception e) + { + return e is ObjectDisposedException; + } + + /// + /// Used to check whether corresponds to a ClassCastException + /// in Java. + /// + /// This exception. + /// true if corresponds to a ClassCastException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsClassCastException(this Exception e) + { + return e is InvalidCastException; + } + + /// + /// Used to check whether corresponds to an EOFException + /// in Java. + /// + /// This exception. + /// true if corresponds to an EOFException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsEOFException(this Exception e) + { + return e is EndOfStreamException; + } + + /// + /// Used to check whether corresponds to an IllegalStateException + /// in Java. + /// + /// This exception. + /// true if corresponds to an IllegalStateException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsIllegalStateException(this Exception e) + { + return e is InvalidOperationException && + !(e is ObjectDisposedException); // In .NET, ObjectDisposedException subclases InvalidOperationException, but Lucene decided to use IOException for AlreadyClosedException + } + + /// + /// Used to check whether corresponds to a StackOverflowError + /// in Java. + /// + /// IMPORTANT: When catching this exception in .NET, put the try catch logic inside of + /// #if FEATURE_STACKOVERFLOWEXCEPTION__ISCATCHABLE blocks because this exception + /// is not catchable on newer flavors of .NET. + /// + /// This exception. + /// true if corresponds to a StackOverflowError type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsStackOverflowError(this Exception e) + { + return e is StackOverflowException; // Uncatchable in .NET core, be sure to use with + } + + /// + /// Used to check whether corresponds to a MissingResourceException + /// in Java. + /// + /// This exception. + /// true if corresponds to a MissingResourceException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsMissingResourceException(this Exception e) + { + return e is MissingManifestResourceException; + } + + /// + /// Used to check whether corresponds to a NoClassDefFoundError + /// in Java. + /// + /// This exception. + /// true if corresponds to a NoClassDefFoundError type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNoClassDefFoundError(this Exception e) + { + return e is TypeLoadException; // LUCENENET NOTE: Not an exact match for Java behavior, but will be thrown if the type or any of its dependencies can't load, which is similar. + } + + /// + /// Used to check whether corresponds to a ClassNotFoundException + /// in Java. + /// + /// This exception. + /// true if corresponds to a ClassNotFoundException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsClassNotFoundException(this Exception e) + { + return e is TypeLoadException; // LUCENENET NOTE: In the case of calling Activator.CreateInstance when the type string doesn't exist, this is the expected exception (there may be other cases to cover here) + } + + /// + /// Used to check whether corresponds to a NoSuchMethodException + /// in Java. + /// + /// This exception. + /// true if corresponds to a NoSuchMethodException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNoSuchMethodException(this Exception e) + { + return e is MissingMethodException; + } + + /// + /// Used to check whether corresponds to a ArithmeticException + /// in Java. + /// + /// This exception. + /// true if corresponds to a ArithmeticException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsArithmeticException(this Exception e) + { + return e is ArithmeticException; + } + + /// + /// Used to check whether corresponds to a AccessDeniedException + /// in Java. + /// + /// This is an a low level IO exception from the underlying operating system when + /// there are insufficient permissions to access a file or folder. + /// + /// This exception. + /// true if corresponds to a AccessDeniedException type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsAccessDeniedException(this Exception e) + { + return e is UnauthorizedAccessException; + } + + /// + /// Used to check whether corresponds to a ServiceConfigurationError + /// in Java. + /// + /// This exception. + /// true if corresponds to a ServiceConfigurationError type + /// in Java; otherwise false. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsServiceConfigurationError(this Exception e) + { + // LUCENENET TODO: Using the internal type here because it is only thrown in AnalysisSPILoader and is not ever likely + // a user will have the problem. Users should catch InvalidOperationException, but we throw ServiceConfigurationError internally + // to identify it as an Error type to our exception handlers. + // Since it is possible that AnalysisSPILoader will someday be factored out in favor of true dependency injection, + // it is not sensible to make a public exception that will be factored out along with it. + return e is ServiceConfigurationError; + } + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/ClassNotFoundException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/ClassNotFoundException.cs new file mode 100644 index 0000000000..59a1a1a740 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/ClassNotFoundException.cs @@ -0,0 +1,104 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// The Java description is: + /// + /// Thrown when an application tries to load in a class through its string name using: + /// + /// The forName method in class Class. + /// The findSystemClass method in class ClassLoader. + /// The loadClass method in class ClassLoader. + /// + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsClassNotFoundException()) + /// + /// + /// IMPORTANT: .NET doesn't behave the same way as Java in this regard. The method + /// may throw if a static initializer fails, but usually returns null if + /// the type is not resolved. So, for compatibility the logic should be adjusted to treat null like a + /// in Java. If the method is expected to throw + /// when the type cannot be resolved, then we must explictly throw it when returns null. + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class ClassNotFoundException : Exception + { + [Obsolete("Use ClassNotFoundException.Create() instead.", error: true)] + public ClassNotFoundException() + { + } + + [Obsolete("Use ClassNotFoundException.Create() instead.", error: true)] + public ClassNotFoundException(string message) : base(message) + { + } + + [Obsolete("Use ClassNotFoundException.Create() instead.", error: true)] + public ClassNotFoundException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use ClassNotFoundException.Create() instead.", error: true)] + public ClassNotFoundException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected ClassNotFoundException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new TypeLoadException(); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new TypeLoadException(message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new TypeLoadException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new TypeLoadException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/CloneNotSupportedException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/CloneNotSupportedException.cs new file mode 100644 index 0000000000..220318cb46 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/CloneNotSupportedException.cs @@ -0,0 +1,26 @@ +using System; + +namespace Lucene +{ + /* + * 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. + */ + + [Obsolete("The MemberwiseClone() method in .NET does not throw exceptions. Remove the try-catch block and any reference to this error, as it is not required in .NET.")] + internal class CloneNotSupportedException + { + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/IOExceptions/AlreadyClosedException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/IOExceptions/AlreadyClosedException.cs new file mode 100644 index 0000000000..38f5e952d8 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/IOExceptions/AlreadyClosedException.cs @@ -0,0 +1,89 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown when there is an attempt to access something that has already been closed. + /// + /// This is a Lucene compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsAlreadyClosedException()) + /// + /// Lucene made a custom type for this, but in .NET we just + /// use the that is built-in, which is what is returned from + /// overlaods of . + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class AlreadyClosedException : ObjectDisposedException + { + [Obsolete("Use AlreadyClosedException.Create() instead.", error: true)] + public AlreadyClosedException(string message) : base(message) + { + } + + [Obsolete("Use AlreadyClosedException.Create() instead.", error: true)] + public AlreadyClosedException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use AlreadyClosedException.Create() instead.", error: true)] + public AlreadyClosedException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected AlreadyClosedException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new ObjectDisposedException(objectName: null, message); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string objectName, string message) => new ObjectDisposedException(objectName, message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new ObjectDisposedException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new ObjectDisposedException(cause.Message, cause); + } +} + diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/IOExceptions/EOFException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/IOExceptions/EOFException.cs new file mode 100644 index 0000000000..c4de0c5008 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/IOExceptions/EOFException.cs @@ -0,0 +1,97 @@ +using Lucene.Net.Diagnostics; +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Signals that an end of file or end of stream has been reached unexpectedly during input. + /// + /// This exception is mainly used by data input streams to signal end of stream. Note that + /// many other input operations return a special value on end of stream rather than throwing + /// an exception. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsEOFException()) + /// + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class EOFException : EndOfStreamException + { + [Obsolete("Use EOFException.Create() instead.", error: true)] + public EOFException() + { + } + + [Obsolete("Use EOFException.Create() instead.", error: true)] + public EOFException(string message) : base(message) + { + } + + [Obsolete("Use EOFException.Create() instead.", error: true)] + public EOFException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use EOFException.Create() instead.", error: true)] + public EOFException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected EOFException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new EndOfStreamException(); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new EndOfStreamException(message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new EndOfStreamException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new EndOfStreamException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/NoSuchMethodException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/NoSuchMethodException.cs new file mode 100644 index 0000000000..7d3c284759 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/NoSuchMethodException.cs @@ -0,0 +1,91 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown when a particular method cannot be found. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsNoSuchMethodException()) + /// + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class NoSuchMethodException : MissingMethodException + { + [Obsolete("Use NoSuchMethodException.Create() instead.", error: true)] + public NoSuchMethodException() + { + } + + [Obsolete("Use NoSuchMethodException.Create() instead.", error: true)] + public NoSuchMethodException(string message) : base(message) + { + } + + [Obsolete("Use NoSuchMethodException.Create() instead.", error: true)] + public NoSuchMethodException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use NoSuchMethodException.Create() instead.", error: true)] + public NoSuchMethodException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected NoSuchMethodException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new MissingMethodException(); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new MissingMethodException(message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new MissingMethodException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new MissingMethodException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/ArrayIndexOutOfBoundsException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/ArrayIndexOutOfBoundsException.cs new file mode 100644 index 0000000000..d9ebe4eeb8 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/ArrayIndexOutOfBoundsException.cs @@ -0,0 +1,112 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown to indicate that an array has been accessed with an illegal index. + /// The index is either negative or greater than or equal to the size of the array. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsArrayIndexOutOfBoundsException()) + /// + /// + /// Note that when an array type is translated to .NET that uses an indexer property this[index], + /// we should instead throw for that property only. + /// In all other cases, use an overload of . + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class ArrayIndexOutOfBoundsException : ArgumentOutOfRangeException + { + [Obsolete("Use ArrayIndexOutOfBoundsException.Create() instead.", error: true)] + public ArrayIndexOutOfBoundsException() + { + } + + [Obsolete("Use ArrayIndexOutOfBoundsException.Create() instead.", error: true)] + public ArrayIndexOutOfBoundsException(string message) : base(message) + { + } + + [Obsolete("Use ArrayIndexOutOfBoundsException.Create() instead.", error: true)] + public ArrayIndexOutOfBoundsException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use ArrayIndexOutOfBoundsException.Create() instead.", error: true)] + public ArrayIndexOutOfBoundsException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected ArrayIndexOutOfBoundsException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new ArgumentOutOfRangeException(); + + /// + /// LUCENENET: This overload is for a "direct" translation without passing the name of the argument. In cases where + /// there is no message and there is a useful argument name, it would make more senes to call new ArgumentOutOfRangeException() directly. + /// Since this class is basically intended as training wheels for those who don't want to bother looking up exception types, + /// this is probably a reasonable default. + /// + /// + /// + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new ArgumentOutOfRangeException(paramName: null, message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string paramName, string message) => new ArgumentOutOfRangeException(paramName, message); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string paramName, object actualValue, string message) => new ArgumentOutOfRangeException(paramName, actualValue, message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new ArgumentOutOfRangeException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new ArgumentOutOfRangeException(cause.Message, cause); + } +} + diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IRuntimeException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IRuntimeException.cs new file mode 100644 index 0000000000..93435cd370 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IRuntimeException.cs @@ -0,0 +1,32 @@ +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Used to identify an exception as a Java RuntimeException type. + /// + /// Lucene Exception types need to be identified as an RuntimeException to our exception + /// handling framework when they derive from Error in Java. + /// However, is internal and C# doesn't allow a + /// public exception to subclass an internal one, so as a workaround, + /// add this interface instead and subclass the most logical exception in .NET. + /// + interface IRuntimeException + { + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IllegalArgumentException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IllegalArgumentException.cs new file mode 100644 index 0000000000..bf194e03da --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IllegalArgumentException.cs @@ -0,0 +1,105 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown to indicate that a method has been passed an illegal or inappropriate argument. + /// + /// This is a Java compatibility exception, and can be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsIllegalArgumentException()) + /// + /// + /// Note that in .NET we should aim to provide the specialized + /// and when appropriate, and since both of them subclass + /// these are not breaking changes. Unlike in Java, .NET + /// types also accept a paramName argument to provide more information about the nature of the exception. + /// + /// Note also that in Java it is not common practice to use guard clauses. For this reason, we can improve the code + /// by adding them when we are sure that, for example, null is not a valid argument. + /// is always a bug, is a fail-fast way of avoiding . + /// That said, care must be taken not to disallow null when it is a valid value. The appropriate way to translate is + /// usually to add an additional method overload without the nullable argument and to ensure that the one with the argument is + /// never passed a null value. + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class IllegalArgumentException : ArgumentException + { + public IllegalArgumentException() + { + } + + public IllegalArgumentException(string message) : base(message) + { + } + + public IllegalArgumentException(string message, Exception innerException) : base(message, innerException) + { + } + + public IllegalArgumentException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected IllegalArgumentException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new ArgumentException(); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new ArgumentException(message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new ArgumentException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, string paramName) => new ArgumentException(message, paramName); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, string paramName, Exception innerException) => new ArgumentException(message, paramName, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new ArgumentException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IllegalStateException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IllegalStateException.cs new file mode 100644 index 0000000000..3b1276d5ab --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IllegalStateException.cs @@ -0,0 +1,93 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Signals that a method has been invoked at an illegal or inappropriate time. + /// In other words, the Java environment or Java application is not in an appropriate + /// state for the requested operation. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsIllegalStateException()) + /// + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class IllegalStateException : InvalidOperationException + { + [Obsolete("Use IllegalStateException.Create() instead.", error: true)] + public IllegalStateException() + { + } + + [Obsolete("Use IllegalStateException.Create() instead.", error: true)] + public IllegalStateException(string message) : base(message) + { + } + + [Obsolete("Use IllegalStateException.Create() instead.", error: true)] + public IllegalStateException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use IllegalStateException.Create() instead.", error: true)] + public IllegalStateException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected IllegalStateException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new InvalidOperationException(); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new InvalidOperationException(message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new InvalidOperationException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new InvalidOperationException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IndexOutOfBoundsException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IndexOutOfBoundsException.cs new file mode 100644 index 0000000000..7e52f0634f --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/IndexOutOfBoundsException.cs @@ -0,0 +1,110 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsIndexOutOfBoundsException()) + /// + /// + /// Note that when an array type is translated to .NET that uses an indexer property this[index], + /// we should instead throw for that property only. + /// In all other cases, use an overload of . + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class IndexOutOfBoundsException : ArgumentOutOfRangeException + { + [Obsolete("Use IndexOutOfBoundsException.Create() instead.", error: true)] + public IndexOutOfBoundsException() + { + } + + [Obsolete("Use IndexOutOfBoundsException.Create() instead.", error: true)] + public IndexOutOfBoundsException(string message) : base(message) + { + } + + [Obsolete("Use IndexOutOfBoundsException.Create() instead.", error: true)] + public IndexOutOfBoundsException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use IndexOutOfBoundsException.Create() instead.", error: true)] + public IndexOutOfBoundsException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected IndexOutOfBoundsException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new ArgumentOutOfRangeException(); + + /// + /// LUCENENET: This overload is for a "direct" translation without passing the name of the argument. In cases where + /// there is no message and there is a useful argument name, it would make more senes to call new ArgumentOutOfRangeException() directly. + /// Since this class is basically intended as training wheels for those who don't want to bother looking up exception types, + /// this is probably a reasonable default. + /// + /// + /// + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new ArgumentOutOfRangeException(paramName: null, message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string paramName, string message) => new ArgumentOutOfRangeException(paramName, message); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string paramName, object actualValue, string message) => new ArgumentOutOfRangeException(paramName, actualValue, message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new ArgumentOutOfRangeException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new ArgumentOutOfRangeException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/NoSuchElementException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/NoSuchElementException.cs new file mode 100644 index 0000000000..a8a4c86007 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/NoSuchElementException.cs @@ -0,0 +1,26 @@ +using System; + +namespace Lucene +{ + /* + * 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. + */ + + [Obsolete(".NET enumerators do not throw when there are no more elements. It is recommended to convert iterators into enumerators and use a MoveNext() method that returns false.")] + internal class NoSuchElementException + { + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/NullPointerException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/NullPointerException.cs new file mode 100644 index 0000000000..955d0b8197 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/NullPointerException.cs @@ -0,0 +1,143 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown when an application attempts to use null in a case where an object is required. These include: + /// + /// Calling the instance method of a null object. + /// Accessing or modifying the field of a null object. + /// Taking the length of null as if it were an array. + /// Accessing or modifying the slots of null as if it were an array. + /// Throwing null as if it were a Throwable value. + /// + /// + /// Applications should throw instances of this class to indicate other illegal uses of the + /// null object. NullPointerException objects may be constructed by the virtual machine + /// as if suppression were disabled and/or the stack trace was not writable. + /// + /// This is a Java compatibility exception, and may be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsNullPointerException()) + /// + /// The static method overloads throw , which is + /// what we should throw in guard clauses. However, there are edge cases where it may make sense to throw + /// instead. One example of this is when in Java an Integer + /// class is set to a primitive int variable. + /// + /// Integer someInt = new Integer(43);
+ /// int primitiveInt = someInt; // Implicit cast by the Java compiler + ///
+ /// If someInt in the above example were set to null, this would still compile, but would + /// throw NullPointerException at runtime. + /// + /// In .NET, Integer is most often translated to int?, making it nullable but keeping it + /// a value type. However setting a nullable int to a nullable one in .NET won't compile. + /// + /// int? someInt = 43;
+ /// int primitiveInt = someInt; // Compile error + ///
+ /// So, to get the same behavior as in Java (provided the nullable cannot be factored away), the + /// appropriate translation would be: + /// + /// int? someInt = 43;
+ /// int primitiveInt;
+ /// if (someInt.HasValue)
+ /// primitiveInt = someInt.Value;
+ /// else
+ /// throw new NullReferenceException(); + ///
+ /// However, do note in most cases it would be better to try to refactor so the nullable + /// (and therefore the exception) isn't required. + /// + /// There are also other edge cases (i.e. null state in the middle of a method where the null value isn't being passed in) + /// where throwing may be more sensible, but this sort of change would need to be tested thoroughly. + ///
+ // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class NullPointerException : ArgumentNullException + { + [Obsolete("Use NullPointerException.Create() instead.", error: true)] + public NullPointerException() + { + } + + [Obsolete("Use NullPointerException.Create() instead.", error: true)] + public NullPointerException(string message) : base(message) + { + } + + [Obsolete("Use NullPointerException.Create() instead.", error: true)] + public NullPointerException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use NullPointerException.Create() instead.", error: true)] + public NullPointerException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected NullPointerException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new ArgumentNullException(); + + /// + /// LUCENENET: This overload is for a "direct" translation without passing the name of the argument. In cases where + /// there is no message and there is a useful argument name, it would make more senes to call new ArgumentNullExcpetion() directly. + /// Since this class is basically intended as training wheels for those who don't want to bother looking up exception types, + /// this is probably a reasonable default. + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new ArgumentNullException(paramName: null, message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string paramName, string message) => new ArgumentNullException(paramName, message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new ArgumentNullException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new ArgumentNullException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/NumberFormatException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/NumberFormatException.cs new file mode 100644 index 0000000000..aafd9cda8a --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/NumberFormatException.cs @@ -0,0 +1,94 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// The Java description is: + /// + /// Thrown to indicate that the application has attempted to convert a string to one of the numeric types, + /// but that the string does not have the appropriate format. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsNumberFormatException()) + /// + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class NumberFormatException : FormatException + { + [Obsolete("Use NumberFormatException.Create() instead.", error: true)] + public NumberFormatException() + { + } + + [Obsolete("Use NumberFormatException.Create() instead.", error: true)] + public NumberFormatException(string message) : base(message) + { + } + + [Obsolete("Use NumberFormatException.Create() instead.", error: true)] + public NumberFormatException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use NumberFormatException.Create() instead.", error: true)] + public NumberFormatException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected NumberFormatException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new FormatException(); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new FormatException(message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new FormatException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new FormatException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/RuntimeException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/RuntimeException.cs new file mode 100644 index 0000000000..e37099b836 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/RuntimeException.cs @@ -0,0 +1,93 @@ +using Lucene.Net.Util; +using System; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// RuntimeException is the superclass of those exceptions that can be thrown during the normal + /// operation of the Java Virtual Machine. + /// + /// RuntimeException and its subclasses are unchecked exceptions.Unchecked exceptions do not + /// need to be declared in a method or constructor's throws clause if they can be thrown by the + /// execution of the method or constructor and propagate outside the method or constructor boundary. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsRuntimeException()) + /// + /// + /// RuntimeException can be thrown, but cannot be subclassed in C# because it is internal. + /// For all Lucene exceptions that subclass RuntimeException, implement the + /// interface, then choose the most logical exception type in .NET to subclass. + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class RuntimeException : Exception, IRuntimeException + { + [Obsolete("Use RuntimeException.Create() instead.", error: true)] + public RuntimeException() + { + } + + [Obsolete("Use RuntimeException.Create() instead.", error: true)] + public RuntimeException(string message) : base(message) + { + } + + [Obsolete("Use RuntimeException.Create() instead.", error: true)] + public RuntimeException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use RuntimeException.Create() instead.", error: true)] + public RuntimeException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected RuntimeException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + public static Exception Create() => new LuceneSystemException(); + + public static Exception Create(string message) => new LuceneSystemException(message); + + public static Exception Create(string message, Exception innerException) => new LuceneSystemException(message, innerException); + + public static Exception Create(Exception cause) => new LuceneSystemException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/StringIndexOutOfBoundsException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/StringIndexOutOfBoundsException.cs new file mode 100644 index 0000000000..6b322048ba --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/StringIndexOutOfBoundsException.cs @@ -0,0 +1,111 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown by String methods to indicate that an index is either negative or greater than the size of the string. + /// For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsStringIndexOutOfBoundsException()) + /// + /// + /// Note that when an array type is translated to .NET that uses an indexer property this[index], + /// we should instead throw for that property only. + /// In all other cases, use an overload of . + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class StringIndexOutOfBoundsException : ArgumentOutOfRangeException + { + [Obsolete("Use StringIndexOutOfBoundsException.Create() instead.", error: true)] + public StringIndexOutOfBoundsException() + { + } + + [Obsolete("Use StringIndexOutOfBoundsException.Create() instead.", error: true)] + public StringIndexOutOfBoundsException(string message) : base(message) + { + } + + [Obsolete("Use StringIndexOutOfBoundsException.Create() instead.", error: true)] + public StringIndexOutOfBoundsException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use StringIndexOutOfBoundsException.Create() instead.", error: true)] + public StringIndexOutOfBoundsException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected StringIndexOutOfBoundsException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new ArgumentOutOfRangeException(); + + /// + /// LUCENENET: This overload is for a "direct" translation without passing the name of the argument. In cases where + /// there is no message and there is a useful argument name, it would make more senes to call new ArgumentOutOfRangeException() directly. + /// Since this class is basically intended as training wheels for those who don't want to bother looking up exception types, + /// this is probably a reasonable default. + /// + /// + /// + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new ArgumentOutOfRangeException(paramName: null, message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string paramName, string message) => new ArgumentOutOfRangeException(paramName, message); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string paramName, object actualValue, string message) => new ArgumentOutOfRangeException(paramName, actualValue, message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new ArgumentOutOfRangeException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new ArgumentOutOfRangeException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/UnsupportedOperationException.cs b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/UnsupportedOperationException.cs new file mode 100644 index 0000000000..4d2f872635 --- /dev/null +++ b/src/Lucene.Net/Support/ExceptionHandling/Exceptions/RuntimeExceptions/UnsupportedOperationException.cs @@ -0,0 +1,93 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace Lucene +{ + /* + * 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. + */ + + /// + /// Thrown to indicate that the requested operation is not supported. + /// + /// This class is a member of the Java Collections Framework. + /// + /// This is a Java compatibility exception, and should be thrown in + /// Lucene.NET everywhere Lucene throws it, however catch blocks should + /// always use the method. + /// + /// catch (Exception ex) when (ex.IsUnsupportedOperationException()) + /// + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class UnsupportedOperationException : NotSupportedException + { + [Obsolete("Use UnsupportedOperationException.Create() instead.", error: true)] + public UnsupportedOperationException() + { + } + + [Obsolete("Use UnsupportedOperationException.Create() instead.", error: true)] + public UnsupportedOperationException(string message) : base(message) + { + } + + [Obsolete("Use UnsupportedOperationException.Create() instead.", error: true)] + public UnsupportedOperationException(string message, Exception innerException) : base(message, innerException) + { + } + + [Obsolete("Use UnsupportedOperationException.Create() instead.", error: true)] + public UnsupportedOperationException(Exception cause) + : base(cause?.ToString(), cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected UnsupportedOperationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + // Static factory methods + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create() => new NotSupportedException(); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message) => new NotSupportedException(message); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(string message, Exception innerException) => new NotSupportedException(message, innerException); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception Create(Exception cause) => new NotSupportedException(cause.Message, cause); + } +} diff --git a/src/Lucene.Net/Support/IO/StreamExtensions.cs b/src/Lucene.Net/Support/IO/StreamExtensions.cs index 2a4d5cafda..f5b9fc0a9f 100644 --- a/src/Lucene.Net/Support/IO/StreamExtensions.cs +++ b/src/Lucene.Net/Support/IO/StreamExtensions.cs @@ -67,9 +67,9 @@ internal static class StreamExtensions /// public static int Read(this Stream stream, ByteBuffer destination, long position) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); - if (destination == null) + if (destination is null) throw new ArgumentNullException(nameof(destination)); if (position < 0) throw new ArgumentOutOfRangeException(nameof(position)); @@ -117,9 +117,9 @@ public static int Read(this Stream stream, ByteBuffer destination, long position public static void Write(this Stream stream, char[] chars) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); - if (chars == null) + if (chars is null) throw new ArgumentNullException(nameof(chars)); byte[] newBytes = new byte[chars.Length * 2]; @@ -134,7 +134,7 @@ public static void Write(this Stream stream, char[] chars) public static char[] ReadChars(this Stream stream, int count) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); @@ -151,7 +151,7 @@ public static char[] ReadChars(this Stream stream, int count) public static void Write(this Stream stream, int value) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); byte[] buff = new byte[4]; @@ -164,7 +164,7 @@ public static void Write(this Stream stream, int value) public static int ReadInt32(this Stream stream) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); byte[] buff = new byte[4]; @@ -175,7 +175,7 @@ public static int ReadInt32(this Stream stream) public static void Write(this Stream stream, long value) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); byte[] buff = new byte[8]; @@ -192,7 +192,7 @@ public static void Write(this Stream stream, long value) public static long ReadInt64(this Stream stream) { - if (stream == null) + if (stream is null) throw new ArgumentNullException(nameof(stream)); byte[] buff = new byte[8]; diff --git a/src/Lucene.Net/Support/ListExtensions.cs b/src/Lucene.Net/Support/ListExtensions.cs index 70a374ece0..b6797a1efb 100644 --- a/src/Lucene.Net/Support/ListExtensions.cs +++ b/src/Lucene.Net/Support/ListExtensions.cs @@ -52,7 +52,7 @@ internal sealed class SubList : IList /// The exclusive ending index. public SubList(IList list, int fromIndex, int toIndex) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); if (fromIndex < 0) throw new ArgumentOutOfRangeException(nameof(fromIndex)); diff --git a/src/Lucene.Net/Support/Number.cs b/src/Lucene.Net/Support/Number.cs index 8b3beb03c0..9aae78d306 100644 --- a/src/Lucene.Net/Support/Number.cs +++ b/src/Lucene.Net/Support/Number.cs @@ -1,4 +1,4 @@ -/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -78,9 +78,9 @@ public static System.String ToString(float f) /// The parsed number in the specified radix. public static long Parse(System.String s, int radix) { - if (s == null) + if (s is null) { - throw new ArgumentException("null"); + throw new ArgumentNullException(nameof(s)); } if (radix < MIN_RADIX) @@ -97,7 +97,7 @@ public static long Parse(System.String s, int radix) long result = 0; long mult = 1; - s = s.ToLowerInvariant(); // LUCENENET TODO: Do we need to deal with Turkish? If so, this won't work right... + s = s.ToLowerInvariant(); for (int i = s.Length - 1; i >= 0; i--) { diff --git a/src/Lucene.Net/Support/Text/StringExtensions.cs b/src/Lucene.Net/Support/Text/StringExtensions.cs index 3886a0e823..eae0842233 100644 --- a/src/Lucene.Net/Support/Text/StringExtensions.cs +++ b/src/Lucene.Net/Support/Text/StringExtensions.cs @@ -35,9 +35,9 @@ internal static class StringExtensions [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool ContainsAny(this string input, char[] charsToCompare) { - if (input == null) + if (input is null) throw new ArgumentNullException(nameof(input)); - if (charsToCompare == null) + if (charsToCompare is null) throw new ArgumentNullException(nameof(charsToCompare)); // Ensure the strings passed don't contain invalid characters diff --git a/src/Lucene.Net/Support/Util/ListExtensions.cs b/src/Lucene.Net/Support/Util/ListExtensions.cs index 407de7dbac..14b275fa7d 100644 --- a/src/Lucene.Net/Support/Util/ListExtensions.cs +++ b/src/Lucene.Net/Support/Util/ListExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace Lucene.Net.Util @@ -36,9 +36,9 @@ public static class ListExtensions /// or is null. public static void AddRange(this IList list, IEnumerable collection) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); - if (collection == null) + if (collection is null) throw new ArgumentNullException(nameof(collection)); if (list is List thisList) diff --git a/src/Lucene.Net/Support/Util/LuceneSystemException.cs b/src/Lucene.Net/Support/Util/LuceneSystemException.cs new file mode 100644 index 0000000000..ae6c18c513 --- /dev/null +++ b/src/Lucene.Net/Support/Util/LuceneSystemException.cs @@ -0,0 +1,100 @@ +using System; +using System.Runtime.Serialization; + +namespace Lucene.Net.Util +{ + /* + * 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. + */ + + /// + /// A general exception type thrown from Lucene.NET. This corresponds to the + /// RuntimeException + /// type in Java. + /// + /// In .NET, is similar, but includes types such as + /// that Java does not include. Per the Microsoft documentation: + /// + /// "Because serves as the base class of a variety of exception types, your code + /// should not throw a exception, nor should it attempt to handle a + /// exception unless you intend to re-throw the original exception." + /// + /// However, since we are not throwing the original exception, we are making a best effort by wrapping it in a custom + /// exception that derives from . This will allow for code to catch + /// for auditing or logging purposes to continue doing so without missing these exceptions. + /// + /// Lucene.NET will throw this exception with an populated with the actual + /// exception (normally a in .NET). + /// The primary reason for throwing a wrapper exception is to eliminate the possibility that the exception will be caught + /// in one of the numerous catch blocks in Lucene unintentionally, and this is a way to preserve the stack trace + /// of the original exception when it is rethrown. + /// + // LUCENENET: It is no longer good practice to use binary serialization. + // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 +#if FEATURE_SERIALIZABLE_EXCEPTIONS + [Serializable] +#endif + internal class LuceneSystemException : SystemException, IRuntimeException + { + /// + /// Initializes a new instance of . + /// + public LuceneSystemException() + { + } + + /// + /// Initializes a new instance of + /// with the specified . + /// + /// The message that describes the error. + public LuceneSystemException(string message) : base(message) + { + } + + /// + /// Initializes a new instance of + /// with the specified and . + /// + /// The message that describes the error. + /// The original . + public LuceneSystemException(string message, Exception innerException) : base(message, innerException) + { + } + + /// + /// Initializes a new instance of + /// with the specified . + /// + /// The original . + public LuceneSystemException(Exception cause) + : base(cause?.Message, cause) + { + } + +#if FEATURE_SERIALIZABLE_EXCEPTIONS + /// + /// Initializes a new instance of this class with serialized data. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected LuceneSystemException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + } +} diff --git a/src/Lucene.Net/Support/WeakDictionary.cs b/src/Lucene.Net/Support/WeakDictionary.cs index c97dbc9ae2..12673adbbb 100644 --- a/src/Lucene.Net/Support/WeakDictionary.cs +++ b/src/Lucene.Net/Support/WeakDictionary.cs @@ -1,4 +1,4 @@ -/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -257,7 +257,7 @@ private class WeakKey where T : class public WeakKey(T key) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); hashCode = key.GetHashCode(); @@ -271,7 +271,7 @@ public override int GetHashCode() public override bool Equals(object obj) { - if (!reference.IsAlive || obj == null) return false; + if (!reference.IsAlive || obj is null) return false; if (object.ReferenceEquals(this, obj)) { diff --git a/src/Lucene.Net/Util/ArrayUtil.cs b/src/Lucene.Net/Util/ArrayUtil.cs index d445237479..8e5b8bc2a4 100644 --- a/src/Lucene.Net/Util/ArrayUtil.cs +++ b/src/Lucene.Net/Util/ArrayUtil.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -95,17 +95,17 @@ public static int ParseInt32(char[] chars, int offset, int len, int radix) int minRadix = 2, maxRadix = 36; if (chars == null || radix < minRadix || radix > maxRadix) { - throw new FormatException(); + throw NumberFormatException.Create(); } int i = 0; if (len == 0) { - throw new FormatException("chars length is 0"); + throw NumberFormatException.Create("chars length is 0"); } bool negative = chars[offset + i] == '-'; if (negative && ++i == len) { - throw new FormatException("can't convert to an int"); + throw NumberFormatException.Create("can't convert to an int"); } if (negative == true) { @@ -124,16 +124,16 @@ private static int Parse(char[] chars, int offset, int len, int radix, bool nega int digit = (int)char.GetNumericValue(chars[i + offset]); if (digit == -1) { - throw new FormatException("Unable to parse"); + throw NumberFormatException.Create("Unable to parse"); } if (max > result) { - throw new FormatException("Unable to parse"); + throw NumberFormatException.Create("Unable to parse"); } int next = result * radix - digit; if (next > result) { - throw new FormatException("Unable to parse"); + throw NumberFormatException.Create("Unable to parse"); } result = next; } @@ -144,7 +144,7 @@ private static int Parse(char[] chars, int offset, int len, int radix, bool nega result = -result; if (result < 0) { - throw new FormatException("Unable to parse"); + throw NumberFormatException.Create("Unable to parse"); } } return result; @@ -177,7 +177,7 @@ public static int Oversize(int minTargetSize, int bytesPerElement) if (minTargetSize < 0) { // catch usage that accidentally overflows int - throw new ArgumentException("invalid array size " + minTargetSize); + throw new ArgumentOutOfRangeException(nameof(minTargetSize), "invalid array size " + minTargetSize + ", may not be < 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (minTargetSize == 0) @@ -772,9 +772,12 @@ public static bool Equals(int[] left, int offsetLeft, int[] right, int offsetRig return false; } + // LUCENENET: The toIntArray() method was only here to convert Integer[] to int[] in Java, but is not necessary when dealing with + /// /// NOTE: This was toIntArray() in Lucene /// + [Obsolete("This API was only to address a compatibility problem with the port and is no longer necessary. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static int[] ToInt32Array(ICollection ints) { int[] result = new int[ints.Count]; diff --git a/src/Lucene.Net/Util/AttributeImpl.cs b/src/Lucene.Net/Util/AttributeImpl.cs index a5cca7e9fc..c75e78613b 100644 --- a/src/Lucene.Net/Util/AttributeImpl.cs +++ b/src/Lucene.Net/Util/AttributeImpl.cs @@ -125,7 +125,7 @@ public virtual void ReflectWith(IAttributeReflector reflector) // LUCENENET NOTE if (interfaces.Count != 1) { - throw new NotSupportedException(clazz.Name + " implements more than one Attribute interface, the default ReflectWith() implementation cannot handle this."); + throw UnsupportedOperationException.Create(clazz.Name + " implements more than one Attribute interface, the default ReflectWith() implementation cannot handle this."); } interfaces.First.Value.TryGetTarget(out Type interf); @@ -142,9 +142,11 @@ public virtual void ReflectWith(IAttributeReflector reflector) // LUCENENET NOTE reflector.Reflect(interf, f.Name, f.GetValue(this)); } } - catch (MemberAccessException e) + catch (Exception e) when (e.IsIllegalAccessException()) { - throw new Exception(e.ToString(), e); + // this should never happen, because we're just accessing fields + // from 'this' + throw RuntimeException.Create(e); } } diff --git a/src/Lucene.Net/Util/AttributeSource.cs b/src/Lucene.Net/Util/AttributeSource.cs index 43ff27d3cc..cda26f44a7 100644 --- a/src/Lucene.Net/Util/AttributeSource.cs +++ b/src/Lucene.Net/Util/AttributeSource.cs @@ -77,7 +77,7 @@ public override Attribute CreateAttributeInstance() // directly rather than using Activator.CreateInstance() return CreateInstance(attributeType) ?? (Attribute)Activator.CreateInstance(attributeType); } - catch (Exception e) + catch (Exception e) when (e.IsInstantiationException() || e.IsIllegalAccessException()) { throw new ArgumentException("Could not instantiate implementing class for " + typeof(S).FullName, e); } @@ -206,9 +206,9 @@ public AttributeSource() /// public AttributeSource(AttributeSource input) { - if (input == null) + if (input is null) { - throw new ArgumentException("input AttributeSource must not be null"); + throw new ArgumentNullException(nameof(input), "input AttributeSource must not be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } this.attributes = input.attributes; this.attributeImpls = input.attributeImpls; @@ -274,7 +274,7 @@ public IteratorAnonymousClass(AttributeSource.State initState) //public virtual void Remove() // LUCENENET specific - not used //{ - // throw new NotSupportedException(); + // throw UnsupportedOperationException.Create(); //} public void Dispose() @@ -296,7 +296,7 @@ public bool MoveNext() public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public Attribute Current => current; @@ -494,7 +494,7 @@ public virtual State CaptureState() /// public void RestoreState(State state) { - if (state == null) + if (state is null) { return; } @@ -684,7 +684,7 @@ public void CopyTo(AttributeSource target) for (State state = GetCurrentState(); state != null; state = state.next) { Attribute targetImpl = target.attributeImpls[state.attribute.GetType()]; - if (targetImpl == null) + if (targetImpl is null) { throw new ArgumentException("this AttributeSource contains Attribute of type " + state.attribute.GetType().Name + " that is not in the target"); } diff --git a/src/Lucene.Net/Util/Automaton/Automaton.cs b/src/Lucene.Net/Util/Automaton/Automaton.cs index 2842cc29c3..8132c6d18f 100644 --- a/src/Lucene.Net/Util/Automaton/Automaton.cs +++ b/src/Lucene.Net/Util/Automaton/Automaton.cs @@ -617,9 +617,12 @@ public virtual int GetNumberOfTransitions() [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { - var other = obj as Automaton; - return BasicOperations.SameLanguage(this, other); - //throw new NotSupportedException("use BasicOperations.sameLanguage instead"); + if (obj is Automaton other) + return BasicOperations.SameLanguage(this, other); + return false; + + // LUCENENET specific - need an Equals implementation for collection equality checking + //throw UnsupportedOperationException.Create("use BasicOperations.sameLanguage instead"); } // LUCENENET specific - in .NET, we can't simply throw an exception here because @@ -667,7 +670,7 @@ public override int GetHashCode() } return hash; - //throw new NotSupportedException(); + //throw UnsupportedOperationException.Create(); } ///// diff --git a/src/Lucene.Net/Util/Automaton/CompiledAutomaton.cs b/src/Lucene.Net/Util/Automaton/CompiledAutomaton.cs index e333b8aa75..3b05bc8489 100644 --- a/src/Lucene.Net/Util/Automaton/CompiledAutomaton.cs +++ b/src/Lucene.Net/Util/Automaton/CompiledAutomaton.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -294,7 +294,7 @@ public virtual TermsEnum GetTermsEnum(Terms terms) AUTOMATON_TYPE.PREFIX => new PrefixTermsEnum(terms.GetEnumerator(), Term),// TODO: this is very likely faster than .intersect, // but we should test and maybe cutover AUTOMATON_TYPE.NORMAL => terms.Intersect(this, null), - _ => throw new Exception("unhandled case"),// unreachable + _ => throw RuntimeException.Create("unhandled case"),// unreachable }; } diff --git a/src/Lucene.Net/Util/Automaton/DaciukMihovAutomatonBuilder.cs b/src/Lucene.Net/Util/Automaton/DaciukMihovAutomatonBuilder.cs index e95abbab14..5e173b40dd 100644 --- a/src/Lucene.Net/Util/Automaton/DaciukMihovAutomatonBuilder.cs +++ b/src/Lucene.Net/Util/Automaton/DaciukMihovAutomatonBuilder.cs @@ -267,7 +267,7 @@ public State Complete() { if (this.stateRegistry == null) { - throw new InvalidOperationException(); + throw IllegalStateException.Create(); } if (root.HasChildren) diff --git a/src/Lucene.Net/Util/Automaton/RegExp.cs b/src/Lucene.Net/Util/Automaton/RegExp.cs index c3d7406aa1..6022e06c56 100644 --- a/src/Lucene.Net/Util/Automaton/RegExp.cs +++ b/src/Lucene.Net/Util/Automaton/RegExp.cs @@ -1,4 +1,4 @@ -using J2N; +using J2N; using J2N.Text; using System; using System.Collections.Generic; @@ -616,7 +616,7 @@ private Automaton ToAutomaton(IDictionary automata, IAutomato { aa = automaton_provider.GetAutomaton(s); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { throw new ArgumentException(e.ToString(), e); } @@ -1289,39 +1289,35 @@ internal RegExp ParseSimpleExp() { throw new ArgumentException("illegal identifier at position " + (pos - 1)); } - try + + // LUCENENET: Refactored so we don't throw exceptions in the normal flow + if (i == 0 || i == s.Length - 1 || i != s.LastIndexOf('-')) { - if (i == 0 || i == s.Length - 1 || i != s.LastIndexOf('-')) - { - throw new FormatException(); - } - string smin = s.Substring(0, i); - string smax = s.Substring(i + 1, s.Length - (i + 1)); - int imin = Convert.ToInt32(smin, CultureInfo.InvariantCulture); - int imax = Convert.ToInt32(smax, CultureInfo.InvariantCulture); - int digits; - if (smin.Length == smax.Length) - { - digits = smin.Length; - } - else - { - digits = 0; - } - if (imin > imax) - { - int t = imin; - imin = imax; - imax = t; - } - return MakeInterval(imin, imax, digits); + throw new ArgumentException("interval syntax error at position " + (pos - 1)); + } + string smin = s.Substring(0, i); + string smax = s.Substring(i + 1, s.Length - (i + 1)); + + if (!int.TryParse(smin, NumberStyles.Integer, CultureInfo.InvariantCulture, out int imin) || + !int.TryParse(smax, NumberStyles.Integer, CultureInfo.InvariantCulture, out int imax)) + throw new ArgumentException("interval syntax error at position " + (pos - 1)); + + int digits; + if (smin.Length == smax.Length) + { + digits = smin.Length; + } + else + { + digits = 0; } -#pragma warning disable 168 - catch (FormatException e) -#pragma warning restore 168 + if (imin > imax) { - throw new ArgumentException("interval syntax error at position " + (pos - 1), e); + int t = imin; + imin = imax; + imax = t; } + return MakeInterval(imin, imax, digits); } } else diff --git a/src/Lucene.Net/Util/Automaton/State.cs b/src/Lucene.Net/Util/Automaton/State.cs index 36f08d0f26..4a7e7cdfa8 100644 --- a/src/Lucene.Net/Util/Automaton/State.cs +++ b/src/Lucene.Net/Util/Automaton/State.cs @@ -127,7 +127,7 @@ public bool MoveNext() public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public void Dispose() diff --git a/src/Lucene.Net/Util/BytesRef.cs b/src/Lucene.Net/Util/BytesRef.cs index 61ad2cea9f..25fabb1982 100644 --- a/src/Lucene.Net/Util/BytesRef.cs +++ b/src/Lucene.Net/Util/BytesRef.cs @@ -367,31 +367,31 @@ public bool IsValid() { if (Bytes == null) { - throw new InvalidOperationException("bytes is null"); + throw IllegalStateException.Create("bytes is null"); } if (Length < 0) { - throw new InvalidOperationException("length is negative: " + Length); + throw IllegalStateException.Create("length is negative: " + Length); } if (Length > Bytes.Length) { - throw new InvalidOperationException("length is out of bounds: " + Length + ",bytes.length=" + Bytes.Length); + throw IllegalStateException.Create("length is out of bounds: " + Length + ",bytes.length=" + Bytes.Length); } if (Offset < 0) { - throw new InvalidOperationException("offset is negative: " + Offset); + throw IllegalStateException.Create("offset is negative: " + Offset); } if (Offset > Bytes.Length) { - throw new InvalidOperationException("offset out of bounds: " + Offset + ",bytes.length=" + Bytes.Length); + throw IllegalStateException.Create("offset out of bounds: " + Offset + ",bytes.length=" + Bytes.Length); } if (Offset + Length < 0) { - throw new InvalidOperationException("offset+length is negative: offset=" + Offset + ",length=" + Length); + throw IllegalStateException.Create("offset+length is negative: offset=" + Offset + ",length=" + Length); } if (Offset + Length > Bytes.Length) { - throw new InvalidOperationException("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",bytes.length=" + Bytes.Length); + throw IllegalStateException.Create("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",bytes.length=" + Bytes.Length); } return true; } @@ -531,7 +531,7 @@ public override string ToString() { return bytesRef.Utf8ToString(); } - catch (IndexOutOfRangeException) + catch (Exception e) when (e.IsIndexOutOfBoundsException()) { return bytesRef.ToString(); } diff --git a/src/Lucene.Net/Util/BytesRefHash.cs b/src/Lucene.Net/Util/BytesRefHash.cs index 8cc1d84fe0..4ff425dacc 100644 --- a/src/Lucene.Net/Util/BytesRefHash.cs +++ b/src/Lucene.Net/Util/BytesRefHash.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -575,7 +575,7 @@ public int ByteStart(int bytesID) #if FEATURE_SERIALIZABLE_EXCEPTIONS [Serializable] #endif - public class MaxBytesLengthExceededException : Exception + public class MaxBytesLengthExceededException : Exception, IRuntimeException // LUCENENET specific: Added IRuntimeException for identification of the Java superclass in .NET { internal MaxBytesLengthExceededException(string message) : base(message) diff --git a/src/Lucene.Net/Util/CharsRef.cs b/src/Lucene.Net/Util/CharsRef.cs index 2b73ea94ff..f24deafbcc 100644 --- a/src/Lucene.Net/Util/CharsRef.cs +++ b/src/Lucene.Net/Util/CharsRef.cs @@ -53,7 +53,7 @@ public sealed class CharsRef : IComparable, ICharSequence, IEquatable< public char[] Chars { get => chars; - set => chars = value ?? throw new ArgumentNullException(nameof(value), "Chars cannot be null"); + set => chars = value ?? throw new ArgumentNullException(nameof(Chars), "Chars cannot be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } private char[] chars; @@ -287,7 +287,7 @@ public char this[int index] // NOTE: must do a real check here to meet the specs of CharSequence if (index < 0 || index >= Length) { - throw new ArgumentOutOfRangeException(nameof(index)); // LUCENENET: Changed exception type to ArgumentOutOfRangeException + throw new ArgumentOutOfRangeException(nameof(index)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } return chars[Offset + index]; } @@ -407,31 +407,31 @@ public bool IsValid() { if (Chars == null) { - throw new InvalidOperationException("chars is null"); + throw IllegalStateException.Create("chars is null"); } if (Length < 0) { - throw new InvalidOperationException("Length is negative: " + Length); + throw IllegalStateException.Create("Length is negative: " + Length); } if (Length > Chars.Length) { - throw new InvalidOperationException("Length is out of bounds: " + Length + ",chars.Length=" + Chars.Length); + throw IllegalStateException.Create("Length is out of bounds: " + Length + ",chars.Length=" + Chars.Length); } if (Offset < 0) { - throw new InvalidOperationException("offset is negative: " + Offset); + throw IllegalStateException.Create("offset is negative: " + Offset); } if (Offset > Chars.Length) { - throw new InvalidOperationException("offset out of bounds: " + Offset + ",chars.Length=" + Chars.Length); + throw IllegalStateException.Create("offset out of bounds: " + Offset + ",chars.Length=" + Chars.Length); } if (Offset + Length < 0) { - throw new InvalidOperationException("offset+Length is negative: offset=" + Offset + ",Length=" + Length); + throw IllegalStateException.Create("offset+Length is negative: offset=" + Offset + ",Length=" + Length); } if (Offset + Length > Chars.Length) { - throw new InvalidOperationException("offset+Length out of bounds: offset=" + Offset + ",Length=" + Length + ",chars.Length=" + Chars.Length); + throw IllegalStateException.Create("offset+Length out of bounds: offset=" + Offset + ",Length=" + Length + ",chars.Length=" + Chars.Length); } return true; } diff --git a/src/Lucene.Net/Util/CloseableThreadLocal.cs b/src/Lucene.Net/Util/CloseableThreadLocal.cs index e819252c39..507bd3b4a0 100644 --- a/src/Lucene.Net/Util/CloseableThreadLocal.cs +++ b/src/Lucene.Net/Util/CloseableThreadLocal.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -92,7 +92,7 @@ public ICollection Values get { if (_disposed) - throw new ObjectDisposedException(nameof(DisposableThreadLocal)); + throw AlreadyClosedException.Create(nameof(DisposableThreadLocal), message: null); return _values.Values; } } @@ -107,7 +107,7 @@ public bool IsValueCreated get { if (_disposed) - throw new ObjectDisposedException(nameof(DisposableThreadLocal)); + throw AlreadyClosedException.Create(nameof(DisposableThreadLocal), message: null); return _state != null && _values.ContainsKey(_state.selfReference); } @@ -134,7 +134,7 @@ public T Value get { if (_disposed) - throw new ObjectDisposedException(nameof(DisposableThreadLocal)); + throw AlreadyClosedException.Create(nameof(DisposableThreadLocal), message: null); (_state ??= new CurrentThreadState()).Register(this); if (_values.TryGetValue(_state.selfReference, out var v) == false && _valueFactory != null) @@ -148,7 +148,7 @@ public T Value set { if (_disposed) - throw new ObjectDisposedException(nameof(DisposableThreadLocal)); + throw AlreadyClosedException.Create(nameof(DisposableThreadLocal), message: null); (_state ??= new CurrentThreadState()).Register(this); _values[_state.selfReference] = value; diff --git a/src/Lucene.Net/Util/CommandLineUtil.cs b/src/Lucene.Net/Util/CommandLineUtil.cs index 6aae655a8b..2b844a7fc2 100644 --- a/src/Lucene.Net/Util/CommandLineUtil.cs +++ b/src/Lucene.Net/Util/CommandLineUtil.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; @@ -40,17 +40,22 @@ public static FSDirectory NewFSDirectory(string clazzName, DirectoryInfo dir) try { Type clazz = LoadFSDirectoryClass(clazzName); + + // LUCENENET: In .NET, we get a null when the class is not found, so we need to throw here for compatibility + if (clazz is null) + throw new ArgumentException(typeof(FSDirectory).Name + " implementation not found: " + clazzName); + return NewFSDirectory(clazz, dir); } - catch (TypeLoadException e) + catch (Exception e) when (e.IsClassNotFoundException()) { throw new ArgumentException(typeof(FSDirectory).Name + " implementation not found: " + clazzName, e); } - catch (InvalidCastException e) + catch (Exception e) when (e.IsClassCastException()) { throw new ArgumentException(clazzName + " is not a " + typeof(FSDirectory).Name + " implementation", e); } - catch (MissingMethodException e) + catch (Exception e) when (e.IsNoSuchMethodException()) { throw new ArgumentException(clazzName + " constructor with " + typeof(FileInfo).Name + " as parameter not found", e); } @@ -84,7 +89,7 @@ public static Type LoadFSDirectoryClass(string clazzName) private static string AdjustDirectoryClassName(string clazzName) { - if (clazzName == null || clazzName.Trim().Length == 0) + if (clazzName is null || clazzName.Trim().Length == 0) { throw new ArgumentException("The " + typeof(FSDirectory).Name + " implementation cannot be null or empty"); } diff --git a/src/Lucene.Net/Util/FieldCacheSanityChecker.cs b/src/Lucene.Net/Util/FieldCacheSanityChecker.cs index 784fcfeebd..50ca9ba6bf 100644 --- a/src/Lucene.Net/Util/FieldCacheSanityChecker.cs +++ b/src/Lucene.Net/Util/FieldCacheSanityChecker.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Search; +using Lucene.Net.Search; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -315,7 +315,7 @@ private static IList GetAllDescendantReaderKeys(object seed) // LUCENENE } } } - catch (ObjectDisposedException) + catch (Exception ace) when (ace.IsAlreadyClosedException()) { // ignore this reader } @@ -377,7 +377,8 @@ public sealed class Insanity public Insanity(InsanityType type, string msg, params FieldCache.CacheEntry[] entries) { - // LUCENENET specific - rearranged order to take advantage of throw expressions + // LUCENENET specific - rearranged order to take advantage of throw expressions and + // changed from IllegalArgumentException to ArgumentNullException (.NET convention) this.type = type ?? throw new ArgumentNullException(nameof(type), "Insanity requires non-null InsanityType"); this.entries = entries ?? throw new ArgumentNullException(nameof(entries), "Insanity requires non-null CacheEntry[]"); if (0 == entries.Length) diff --git a/src/Lucene.Net/Util/Fst/FST.cs b/src/Lucene.Net/Util/Fst/FST.cs index d405d4305b..f2b2d7e678 100644 --- a/src/Lucene.Net/Util/Fst/FST.cs +++ b/src/Lucene.Net/Util/Fst/FST.cs @@ -242,7 +242,7 @@ public FST(DataInput @in, Outputs outputs, int maxBlockBits) if (maxBlockBits < 1 || maxBlockBits > 30) { - throw new ArgumentException("maxBlockBits should be 1 .. 30; got " + maxBlockBits); + throw new ArgumentOutOfRangeException(nameof(maxBlockBits), "maxBlockBits should be 1 .. 30; got " + maxBlockBits); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } // NOTE: only reads most recent format; we don't have @@ -286,7 +286,7 @@ public FST(DataInput @in, Outputs outputs, int maxBlockBits) 0 => FST.INPUT_TYPE.BYTE1, 1 => FST.INPUT_TYPE.BYTE2, 2 => FST.INPUT_TYPE.BYTE4, - _ => throw new InvalidOperationException("invalid input type " + t), + _ => throw IllegalStateException.Create("invalid input type " + t), }; if (packed) { @@ -347,7 +347,7 @@ internal void Finish(long newStartNode) { if (startNode != -1) { - throw new InvalidOperationException("already finished"); + throw IllegalStateException.Create("already finished"); } if (newStartNode == FST.FINAL_END_NODE && !EqualityComparer.Default.Equals(emptyOutput, default)) { @@ -482,15 +482,15 @@ public void Save(DataOutput @out) { if (startNode == -1) { - throw new InvalidOperationException("call finish first"); + throw IllegalStateException.Create("call finish first"); } if (nodeAddress != null) { - throw new InvalidOperationException("cannot save an FST pre-packed FST; it must first be packed"); + throw IllegalStateException.Create("cannot save an FST pre-packed FST; it must first be packed"); } if (packed && !(nodeRefToAddress is PackedInt32s.Mutable)) { - throw new InvalidOperationException("cannot save a FST which has been loaded from disk "); + throw IllegalStateException.Create("cannot save a FST which has been loaded from disk "); } CodecUtil.WriteHeader(@out, FST.FILE_FORMAT_NAME, FST.VERSION_CURRENT); if (packed) @@ -834,7 +834,7 @@ internal long AddNode(Builder.UnCompiledNode nodeIn) // > 2.1B nodes when packing: if (nodeAddress != null && nodeCount == int.MaxValue) { - throw new InvalidOperationException("cannot create a packed FST with more than 2.1 billion nodes"); + throw IllegalStateException.Create("cannot create a packed FST with more than 2.1 billion nodes"); } nodeCount++; @@ -1089,7 +1089,7 @@ public FST.Arc ReadNextArc(FST.Arc arc, FST.BytesReader @in) // this was a fake inserted "final" arc if (arc.NextArc <= 0) { - throw new ArgumentException("cannot readNextArc when arc.isLast()=true"); + throw new ArgumentException("cannot readNextArc when arc.IsLast=true"); } return ReadFirstRealTargetArc(arc.NextArc, arc, @in); } @@ -1668,7 +1668,7 @@ internal FST Pack(int minInCountDeref, int maxDerefNodes, float acceptableOve // - use spare bits in flags.... for top few labels / // outputs / targets - if (nodeAddress == null) + if (nodeAddress is null) { throw new ArgumentException("this FST was not built with willPackFST=true"); } diff --git a/src/Lucene.Net/Util/Fst/Outputs.cs b/src/Lucene.Net/Util/Fst/Outputs.cs index 634faf54c8..efe852d94f 100644 --- a/src/Lucene.Net/Util/Fst/Outputs.cs +++ b/src/Lucene.Net/Util/Fst/Outputs.cs @@ -102,7 +102,7 @@ public virtual T ReadFinalOutput(DataInput @in) [MethodImpl(MethodImplOptions.NoInlining)] public virtual T Merge(T first, T second) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } } } \ No newline at end of file diff --git a/src/Lucene.Net/Util/IOUtils.cs b/src/Lucene.Net/Util/IOUtils.cs index f5eff8ee45..7ca4af7d03 100644 --- a/src/Lucene.Net/Util/IOUtils.cs +++ b/src/Lucene.Net/Util/IOUtils.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; using System.Text; namespace Lucene.Net.Util @@ -179,7 +180,7 @@ public static void DisposeWhileHandlingException(Exception priorException, param @object.Dispose(); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { AddSuppressed(priorException ?? th, t); if (th == null) @@ -191,7 +192,7 @@ public static void DisposeWhileHandlingException(Exception priorException, param if (priorException != null) { - throw priorException; + ExceptionDispatchInfo.Capture(priorException).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } else { @@ -216,7 +217,7 @@ public static void DisposeWhileHandlingException(Exception priorException, IEnum @object.Dispose(); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { AddSuppressed(priorException ?? th, t); if (th == null) @@ -228,7 +229,7 @@ public static void DisposeWhileHandlingException(Exception priorException, IEnum if (priorException != null) { - throw priorException; + ExceptionDispatchInfo.Capture(priorException).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } else { @@ -259,7 +260,7 @@ public static void Dispose(params IDisposable[] objects) @object.Dispose(); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { AddSuppressed(th, t); if (th == null) @@ -289,7 +290,7 @@ public static void Dispose(IEnumerable objects) @object.Dispose(); } } - catch (Exception t) + catch (Exception t) when (t.IsThrowable()) { AddSuppressed(th, t); if (th == null) @@ -320,7 +321,7 @@ public static void DisposeWhileHandlingException(params IDisposable[] objects) o.Dispose(); } } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { //eat it } @@ -342,7 +343,7 @@ public static void DisposeWhileHandlingException(IEnumerable object @object.Dispose(); } } - catch (Exception) + catch (Exception t) when (t.IsThrowable()) { //eat it } @@ -462,7 +463,7 @@ public static void DeleteFilesIgnoringExceptions(Directory dir, params string[] { dir.DeleteFile(name); } - catch (Exception) + catch (Exception ignored) when (ignored.IsThrowable()) { // ignore } @@ -505,9 +506,9 @@ public static void ReThrow(Exception th) { if (th != null) { - if (th is IOException) + if (th.IsIOException()) { - throw th; + ExceptionDispatchInfo.Capture(th).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw } ReThrowUnchecked(th); } @@ -522,81 +523,16 @@ public static void ReThrowUnchecked(Exception th) { if (th != null) { - throw th; + if (th.IsRuntimeException()) + ExceptionDispatchInfo.Capture(th).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw + if (th.IsError()) + ExceptionDispatchInfo.Capture(th).Throw(); // LUCENENET: Rethrow to preserve stack details from the original throw + throw RuntimeException.Create(th); } } // LUCENENET specific: Fsync is pointless in .NET, since we are // calling FileStream.Flush(true) before the stream is disposed // which means we never need it at the point in Java where it is called. - // /// - // /// Ensure that any writes to the given file is written to the storage device that contains it. - // /// The file to fsync - // /// If true, the given file is a directory (we open for read and ignore s, - // /// because not all file systems and operating systems allow to fsync on a directory) - // public static void Fsync(string fileToSync, bool isDir) - // { - // // Fsync does not appear to function properly for Windows and Linux platforms. In Lucene version - // // they catch this in IOException branch and return if the call is for the directory. - // // In Lucene.Net the exception is UnauthorizedAccessException and is not handled by - // // IOException block. No need to even attempt to fsync, just return if the call is for directory - // if (isDir) - // { - // return; - // } - - // var retryCount = 1; - // while (true) - // { - // FileStream file = null; - // bool success = false; - // try - // { - // // If the file is a directory we have to open read-only, for regular files we must open r/w for the fsync to have an effect. - // // See http://blog.httrack.com/blog/2013/11/15/everything-you-always-wanted-to-know-about-fsync/ - // file = new FileStream(fileToSync, - // FileMode.Open, // We shouldn't create a file when syncing. - // // Java version uses FileChannel which doesn't create the file if it doesn't already exist, - // // so there should be no reason for attempting to create it in Lucene.Net. - // FileAccess.Write, - // FileShare.ReadWrite); - // //FileSupport.Sync(file); - // file.Flush(true); - // success = true; - // } - // catch (IOException e) - // { - // if (retryCount == 5) - // { - // throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) - // } - // try - // { - // // Pause 5 msec - // Thread.Sleep(5); - // } - // catch (ThreadInterruptedException ie) - // { - // var ex = new ThreadInterruptedException(ie.ToString(), ie); - // ex.AddSuppressed(e); - // throw ex; - // } - // } - // finally - // { - // if (file != null) - // { - // file.Dispose(); - // } - // } - - // if (success) - // { - // return; - // } - - // retryCount++; - // } - // } } } \ No newline at end of file diff --git a/src/Lucene.Net/Util/InfoStream.cs b/src/Lucene.Net/Util/InfoStream.cs index eff6c1454a..7643ef565c 100644 --- a/src/Lucene.Net/Util/InfoStream.cs +++ b/src/Lucene.Net/Util/InfoStream.cs @@ -78,7 +78,7 @@ public static InfoStream Default lock (typeof(InfoStream)) { defaultInfoStream = value ?? throw new ArgumentNullException( - nameof(value), + nameof(Default), "Cannot set InfoStream default implementation to null. " + "To disable logging use InfoStream.NO_OUTPUT"); } diff --git a/src/Lucene.Net/Util/IntsRef.cs b/src/Lucene.Net/Util/IntsRef.cs index 03e820a45b..a98c482d90 100644 --- a/src/Lucene.Net/Util/IntsRef.cs +++ b/src/Lucene.Net/Util/IntsRef.cs @@ -55,7 +55,7 @@ public sealed class Int32sRef : IComparable // LUCENENET specific: No public int[] Int32s // LUCENENET TODO: API - change to indexer { get => ints; - set => ints = value ?? throw new ArgumentNullException(nameof(value), "Ints should never be null"); + set => ints = value ?? throw new ArgumentNullException(nameof(Int32s), "Int32s should never be null"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } private int[] ints; @@ -262,31 +262,31 @@ public bool IsValid() { if (ints == null) { - throw new InvalidOperationException("ints is null"); + throw IllegalStateException.Create("ints is null"); } if (Length < 0) { - throw new InvalidOperationException("length is negative: " + Length); + throw IllegalStateException.Create("length is negative: " + Length); } if (Length > ints.Length) { - throw new InvalidOperationException("length is out of bounds: " + Length + ",ints.length=" + Int32s.Length); + throw IllegalStateException.Create("length is out of bounds: " + Length + ",ints.length=" + Int32s.Length); } if (Offset < 0) { - throw new InvalidOperationException("offset is negative: " + Offset); + throw IllegalStateException.Create("offset is negative: " + Offset); } if (Offset > ints.Length) { - throw new InvalidOperationException("offset out of bounds: " + Offset + ",ints.length=" + Int32s.Length); + throw IllegalStateException.Create("offset out of bounds: " + Offset + ",ints.length=" + Int32s.Length); } if (Offset + Length < 0) { - throw new InvalidOperationException("offset+length is negative: offset=" + Offset + ",length=" + Length); + throw IllegalStateException.Create("offset+length is negative: offset=" + Offset + ",length=" + Length); } if (Offset + Length > Int32s.Length) { - throw new InvalidOperationException("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",ints.length=" + Int32s.Length); + throw IllegalStateException.Create("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",ints.length=" + Int32s.Length); } return true; } diff --git a/src/Lucene.Net/Util/LongsRef.cs b/src/Lucene.Net/Util/LongsRef.cs index 9dc0f19668..46a51d6c30 100644 --- a/src/Lucene.Net/Util/LongsRef.cs +++ b/src/Lucene.Net/Util/LongsRef.cs @@ -56,7 +56,7 @@ public sealed class Int64sRef : IComparable // LUCENENET specific: No public long[] Int64s { get => longs; - set => longs = value ?? throw new ArgumentNullException(nameof(value)); + set => longs = value ?? throw new ArgumentNullException(nameof(Int64s)); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } private long[] longs; @@ -262,31 +262,31 @@ public bool IsValid() { if (longs == null) { - throw new InvalidOperationException("longs is null"); + throw IllegalStateException.Create("longs is null"); } if (Length < 0) { - throw new InvalidOperationException("length is negative: " + Length); + throw IllegalStateException.Create("length is negative: " + Length); } if (Length > longs.Length) { - throw new InvalidOperationException("length is out of bounds: " + Length + ",longs.length=" + longs.Length); + throw IllegalStateException.Create("length is out of bounds: " + Length + ",longs.length=" + longs.Length); } if (Offset < 0) { - throw new InvalidOperationException("offset is negative: " + Offset); + throw IllegalStateException.Create("offset is negative: " + Offset); } if (Offset > longs.Length) { - throw new InvalidOperationException("offset out of bounds: " + Offset + ",longs.length=" + longs.Length); + throw IllegalStateException.Create("offset out of bounds: " + Offset + ",longs.length=" + longs.Length); } if (Offset + Length < 0) { - throw new InvalidOperationException("offset+length is negative: offset=" + Offset + ",length=" + Length); + throw IllegalStateException.Create("offset+length is negative: offset=" + Offset + ",length=" + Length); } if (Offset + Length > longs.Length) { - throw new InvalidOperationException("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",longs.length=" + longs.Length); + throw IllegalStateException.Create("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",longs.length=" + longs.Length); } return true; } diff --git a/src/Lucene.Net/Util/MathUtil.cs b/src/Lucene.Net/Util/MathUtil.cs index 86b3fc245a..799e23515a 100644 --- a/src/Lucene.Net/Util/MathUtil.cs +++ b/src/Lucene.Net/Util/MathUtil.cs @@ -34,7 +34,7 @@ public static int Log(long x, int @base) { if (@base <= 1) { - throw new ArgumentException("base must be > 1"); + throw new ArgumentOutOfRangeException(nameof(@base), "base must be > 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } int ret = 0; while (x >= @base) diff --git a/src/Lucene.Net/Util/MergedIterator.cs b/src/Lucene.Net/Util/MergedIterator.cs index 2216c7563d..99860a073a 100644 --- a/src/Lucene.Net/Util/MergedIterator.cs +++ b/src/Lucene.Net/Util/MergedIterator.cs @@ -109,7 +109,7 @@ public bool MoveNext() public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public void Dispose() @@ -271,7 +271,7 @@ public bool MoveNext() public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public void Dispose() diff --git a/src/Lucene.Net/Util/NamedSPILoader.cs b/src/Lucene.Net/Util/NamedSPILoader.cs index 44537e7d4a..3e124afb76 100644 --- a/src/Lucene.Net/Util/NamedSPILoader.cs +++ b/src/Lucene.Net/Util/NamedSPILoader.cs @@ -1,4 +1,4 @@ -// LUCENENET specific - removed this class and replaced it with abstract factories +// LUCENENET specific - removed this class and replaced it with abstract factories // DefaultCodecFactory, DefaultDocValuesFormatFactory, and DefaultPostingsFormatFactory // and their common base class, NamedServiceFactory. // The factories have a more efficient default scanning implementation and make @@ -83,7 +83,7 @@ // } // catch (Exception e) // { -// throw new InvalidOperationException("Cannot instantiate SPI class: " + c.Name, e); +// throw ServiceConfigurationError.Create("Cannot instantiate SPI class: " + c.Name, e); // } // } // this.services = Collections.UnmodifiableMap(services); diff --git a/src/Lucene.Net/Util/NumericUtils.cs b/src/Lucene.Net/Util/NumericUtils.cs index 54b969be28..269e7dbcd8 100644 --- a/src/Lucene.Net/Util/NumericUtils.cs +++ b/src/Lucene.Net/Util/NumericUtils.cs @@ -1,4 +1,4 @@ -using J2N.Numerics; +using J2N.Numerics; using System; using System.Runtime.CompilerServices; @@ -151,7 +151,7 @@ public static void Int64ToPrefixCodedBytes(long val, int shift, BytesRef bytes) { if ((shift & ~0x3f) != 0) // ensure shift is 0..63 { - throw new ArgumentException("Illegal shift value, must be 0..63"); + throw new ArgumentOutOfRangeException(nameof(shift), "Illegal shift value, must be 0..63"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } int nChars = (((63 - shift) * 37) >> 8) + 1; // i/7 is the same as (i*37)>>8 for i in 0..63 bytes.Offset = 0; @@ -186,7 +186,7 @@ public static void Int32ToPrefixCodedBytes(int val, int shift, BytesRef bytes) { if ((shift & ~0x1f) != 0) // ensure shift is 0..31 { - throw new ArgumentException("Illegal shift value, must be 0..31"); + throw new ArgumentOutOfRangeException(nameof(shift), "Illegal shift value, must be 0..31"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } int nChars = (((31 - shift) * 37) >> 8) + 1; // i/7 is the same as (i*37)>>8 for i in 0..63 bytes.Offset = 0; @@ -220,7 +220,7 @@ public static int GetPrefixCodedInt64Shift(BytesRef val) int shift = val.Bytes[val.Offset] - SHIFT_START_INT64; if (shift > 63 || shift < 0) { - throw new FormatException("Invalid shift value (" + shift + ") in prefixCoded bytes (is encoded value really an INT?)"); + throw NumberFormatException.Create("Invalid shift value (" + shift + ") in prefixCoded bytes (is encoded value really an INT?)"); } return shift; } @@ -238,7 +238,7 @@ public static int GetPrefixCodedInt32Shift(BytesRef val) int shift = val.Bytes[val.Offset] - SHIFT_START_INT32; if (shift > 31 || shift < 0) { - throw new FormatException("Invalid shift value in prefixCoded bytes (is encoded value really an INT?)"); + throw NumberFormatException.Create("Invalid shift value in prefixCoded bytes (is encoded value really an INT?)"); } return shift; } @@ -262,7 +262,7 @@ public static long PrefixCodedToInt64(BytesRef val) var b = val.Bytes[i]; if (b < 0) { - throw new FormatException("Invalid prefixCoded numerical value representation (byte " + (b & 0xff).ToString("x") + " at position " + (i - val.Offset) + " is invalid)"); + throw NumberFormatException.Create("Invalid prefixCoded numerical value representation (byte " + (b & 0xff).ToString("x") + " at position " + (i - val.Offset) + " is invalid)"); } sortableBits |= (byte)b; } @@ -288,7 +288,7 @@ public static int PrefixCodedToInt32(BytesRef val) var b = val.Bytes[i]; if (b < 0) { - throw new FormatException("Invalid prefixCoded numerical value representation (byte " + (b & 0xff).ToString("x") + " at position " + (i - val.Offset) + " is invalid)"); + throw NumberFormatException.Create("Invalid prefixCoded numerical value representation (byte " + (b & 0xff).ToString("x") + " at position " + (i - val.Offset) + " is invalid)"); } sortableBits |= b; } @@ -411,7 +411,7 @@ private static void SplitRange(object builder, int valSize, int precisionStep, l { if (precisionStep < 1) { - throw new ArgumentException("precisionStep must be >=1"); + throw new ArgumentOutOfRangeException(nameof(precisionStep), "precisionStep must be >=1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (minBound > maxBound) { @@ -491,7 +491,7 @@ public abstract class Int64RangeBuilder /// public virtual void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } /// @@ -524,7 +524,7 @@ public abstract class Int32RangeBuilder /// public virtual void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded) { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } /// diff --git a/src/Lucene.Net/Util/OfflineSorter.cs b/src/Lucene.Net/Util/OfflineSorter.cs index 7f299b9cff..490bc624a8 100644 --- a/src/Lucene.Net/Util/OfflineSorter.cs +++ b/src/Lucene.Net/Util/OfflineSorter.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Store; using Lucene.Net.Support.IO; using System; @@ -74,12 +74,12 @@ private BufferSize(long bytes) { if (bytes > int.MaxValue) { - throw new ArgumentException("Buffer too large for Java (" + (int.MaxValue / MB) + "mb max): " + bytes); + throw new ArgumentOutOfRangeException(nameof(bytes), "Buffer too large for .NET (" + (int.MaxValue / MB) + "mb max): " + bytes); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (bytes < ABSOLUTE_MIN_SORT_BUFFER_SIZE) { - throw new ArgumentException(MIN_BUFFER_SIZE_MSG + ": " + bytes); + throw new ArgumentOutOfRangeException(nameof(bytes), MIN_BUFFER_SIZE_MSG + ": " + bytes); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.bytes = (int)bytes; @@ -228,7 +228,7 @@ public OfflineSorter(IComparer comparer, BufferSize ramBufferSize, Dir if (maxTempfiles < 2) { - throw new ArgumentException("maxTempFiles must be >= 2"); + throw new ArgumentOutOfRangeException(nameof(maxTempfiles), "maxTempFiles must be >= 2"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.ramBufferSize = ramBufferSize; @@ -622,12 +622,10 @@ public virtual bool Read(BytesRef @ref) { length = (ushort)inputStream.ReadInt16(); } -#pragma warning disable CA1031 // Do not catch general exception types - catch (EndOfStreamException) + catch (Exception e) when (e.IsEOFException()) { return false; } -#pragma warning restore CA1031 // Do not catch general exception types @ref.Grow(length); @ref.Offset = 0; @@ -650,12 +648,10 @@ public virtual byte[] Read() { length = (ushort)inputStream.ReadInt16(); } -#pragma warning disable CA1031 // Do not catch general exception types - catch (EndOfStreamException) + catch (Exception e) when (e.IsEOFException()) { return null; } -#pragma warning restore CA1031 // Do not catch general exception types if (Debugging.AssertsEnabled) Debugging.Assert(length >= 0, "Sanity: sequence length < 0: {0}", length); byte[] result = new byte[length]; diff --git a/src/Lucene.Net/Util/OpenBitSet.cs b/src/Lucene.Net/Util/OpenBitSet.cs index fe17a3b826..5f6b33322d 100644 --- a/src/Lucene.Net/Util/OpenBitSet.cs +++ b/src/Lucene.Net/Util/OpenBitSet.cs @@ -119,7 +119,7 @@ public OpenBitSet(long[] bits, int numWords) { if (numWords > bits.Length) { - throw new ArgumentException("numWords cannot exceed bits.length"); + throw new ArgumentOutOfRangeException(nameof(numWords), "numWords cannot exceed bits.Length"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.m_bits = bits; this.m_wlen = numWords; diff --git a/src/Lucene.Net/Util/PForDeltaDocIdSet.cs b/src/Lucene.Net/Util/PForDeltaDocIdSet.cs index 84c2a64b3e..3708e30281 100644 --- a/src/Lucene.Net/Util/PForDeltaDocIdSet.cs +++ b/src/Lucene.Net/Util/PForDeltaDocIdSet.cs @@ -114,7 +114,7 @@ public virtual Builder SetIndexInterval(int indexInterval) { if (indexInterval < 1) { - throw new ArgumentException("indexInterval must be >= 1"); + throw new ArgumentOutOfRangeException(nameof(indexInterval), "indexInterval must be >= 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.indexInterval = indexInterval; return this; diff --git a/src/Lucene.Net/Util/Packed/AbstractAppendingLongBuffer.cs b/src/Lucene.Net/Util/Packed/AbstractAppendingLongBuffer.cs index d96859a50a..3a6b0026f3 100644 --- a/src/Lucene.Net/Util/Packed/AbstractAppendingLongBuffer.cs +++ b/src/Lucene.Net/Util/Packed/AbstractAppendingLongBuffer.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using System; using System.Runtime.CompilerServices; @@ -83,7 +83,7 @@ public void Add(long l) { if (pending == null) { - throw new Exception("this buffer is frozen"); + throw IllegalStateException.Create("this buffer is frozen"); } if (pendingOff == pending.Length) { diff --git a/src/Lucene.Net/Util/Packed/AbstractBlockPackedWriter.cs b/src/Lucene.Net/Util/Packed/AbstractBlockPackedWriter.cs index 9d3d85f2bf..bda039dbb4 100644 --- a/src/Lucene.Net/Util/Packed/AbstractBlockPackedWriter.cs +++ b/src/Lucene.Net/Util/Packed/AbstractBlockPackedWriter.cs @@ -88,7 +88,7 @@ private void CheckNotFinished() { if (m_finished) { - throw new InvalidOperationException("Already finished"); + throw IllegalStateException.Create("Already finished"); } } @@ -111,7 +111,7 @@ internal virtual void AddBlockOfZeros() CheckNotFinished(); if (m_off != 0 && m_off != m_values.Length) { - throw new InvalidOperationException("" + m_off); + throw IllegalStateException.Create("" + m_off); } if (m_off == m_values.Length) { diff --git a/src/Lucene.Net/Util/Packed/BlockPackedReader.cs b/src/Lucene.Net/Util/Packed/BlockPackedReader.cs index ac80ba4d43..2625e3fe11 100644 --- a/src/Lucene.Net/Util/Packed/BlockPackedReader.cs +++ b/src/Lucene.Net/Util/Packed/BlockPackedReader.cs @@ -2,6 +2,7 @@ using Lucene.Net.Diagnostics; using Lucene.Net.Store; using System; +using System.IO; namespace Lucene.Net.Util.Packed { @@ -50,7 +51,7 @@ public BlockPackedReader(IndexInput @in, int packedIntsVersion, int blockSize, l int bitsPerValue = token.TripleShift(AbstractBlockPackedWriter.BPV_SHIFT); if (bitsPerValue > 64) { - throw new Exception("Corrupted"); + throw new IOException("Corrupted"); } if ((token & AbstractBlockPackedWriter.MIN_VALUE_EQUALS_0) == 0) { diff --git a/src/Lucene.Net/Util/Packed/BlockPackedReaderIterator.cs b/src/Lucene.Net/Util/Packed/BlockPackedReaderIterator.cs index b35825d4ec..12f16fd6fa 100644 --- a/src/Lucene.Net/Util/Packed/BlockPackedReaderIterator.cs +++ b/src/Lucene.Net/Util/Packed/BlockPackedReaderIterator.cs @@ -146,7 +146,7 @@ public void Skip(long count) if (Debugging.AssertsEnabled) Debugging.Assert(count >= 0); if (ord + count > valueCount || ord + count < 0) { - throw new EndOfStreamException(); + throw EOFException.Create(); } // 1. skip buffered values @@ -219,7 +219,7 @@ public long Next() { if (ord == valueCount) { - throw new EndOfStreamException(); + throw EOFException.Create(); } if (off == blockSize) { @@ -237,7 +237,7 @@ public Int64sRef Next(int count) if (Debugging.AssertsEnabled) Debugging.Assert(count > 0); if (ord == valueCount) { - throw new EndOfStreamException(); + throw EOFException.Create(); } if (off == blockSize) { diff --git a/src/Lucene.Net/Util/Packed/BulkOperation.cs b/src/Lucene.Net/Util/Packed/BulkOperation.cs index 0987bc8c22..713d21037a 100644 --- a/src/Lucene.Net/Util/Packed/BulkOperation.cs +++ b/src/Lucene.Net/Util/Packed/BulkOperation.cs @@ -175,7 +175,7 @@ public static BulkOperation Of(PackedInt32s.Format format, int bitsPerValue) } else { - throw new InvalidOperationException(); + throw AssertionError.Create(); } } diff --git a/src/Lucene.Net/Util/Packed/BulkOperationPacked.cs b/src/Lucene.Net/Util/Packed/BulkOperationPacked.cs index af043856de..156401162b 100644 --- a/src/Lucene.Net/Util/Packed/BulkOperationPacked.cs +++ b/src/Lucene.Net/Util/Packed/BulkOperationPacked.cs @@ -133,7 +133,7 @@ public override void Decode(long[] blocks, int blocksOffset, int[] values, int v { if (bitsPerValue > 32) { - throw new NotSupportedException("Cannot decode " + bitsPerValue + "-bits values into an int[]"); + throw UnsupportedOperationException.Create("Cannot decode " + bitsPerValue + "-bits values into an int[]"); } int bitsLeft = 64; for (int i = 0; i < longValueCount * iterations; ++i) diff --git a/src/Lucene.Net/Util/Packed/BulkOperationPackedSingleBlock.cs b/src/Lucene.Net/Util/Packed/BulkOperationPackedSingleBlock.cs index b09fcbf7d8..c802883214 100644 --- a/src/Lucene.Net/Util/Packed/BulkOperationPackedSingleBlock.cs +++ b/src/Lucene.Net/Util/Packed/BulkOperationPackedSingleBlock.cs @@ -128,7 +128,7 @@ public override void Decode(long[] blocks, int blocksOffset, int[] values, int v { if (bitsPerValue > 32) { - throw new NotSupportedException("Cannot decode " + bitsPerValue + "-bits values into an int[]"); + throw UnsupportedOperationException.Create("Cannot decode " + bitsPerValue + "-bits values into an int[]"); } for (int i = 0; i < iterations; ++i) { @@ -141,7 +141,7 @@ public override void Decode(byte[] blocks, int blocksOffset, int[] values, int v { if (bitsPerValue > 32) { - throw new NotSupportedException("Cannot decode " + bitsPerValue + "-bits values into an int[]"); + throw UnsupportedOperationException.Create("Cannot decode " + bitsPerValue + "-bits values into an int[]"); } for (int i = 0; i < iterations; ++i) { diff --git a/src/Lucene.Net/Util/Packed/DirectPacked64SingleBlockReader.cs b/src/Lucene.Net/Util/Packed/DirectPacked64SingleBlockReader.cs index 4c618b6590..3c9c011526 100644 --- a/src/Lucene.Net/Util/Packed/DirectPacked64SingleBlockReader.cs +++ b/src/Lucene.Net/Util/Packed/DirectPacked64SingleBlockReader.cs @@ -52,9 +52,9 @@ public override long Get(int index) int offsetInBlock = index % valuesPerBlock; return (block.TripleShift(offsetInBlock * m_bitsPerValue)) & mask; } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new InvalidOperationException("failed", e); + throw IllegalStateException.Create("failed", e); } } diff --git a/src/Lucene.Net/Util/Packed/DirectPackedReader.cs b/src/Lucene.Net/Util/Packed/DirectPackedReader.cs index 754ca7c025..74092c87f3 100644 --- a/src/Lucene.Net/Util/Packed/DirectPackedReader.cs +++ b/src/Lucene.Net/Util/Packed/DirectPackedReader.cs @@ -105,13 +105,13 @@ public override long Get(int index) break; default: - throw new InvalidOperationException("bitsPerValue too large: " + m_bitsPerValue); + throw AssertionError.Create("bitsPerValue too large: " + m_bitsPerValue); } return (rawValue.TripleShift(shiftRightBits)) & valueMask; } - catch (IOException ioe) + catch (Exception ioe) when (ioe.IsIOException()) { - throw new InvalidOperationException("failed", ioe); + throw IllegalStateException.Create("failed", ioe); } } diff --git a/src/Lucene.Net/Util/Packed/EliasFanoDecoder.cs b/src/Lucene.Net/Util/Packed/EliasFanoDecoder.cs index acdf86e049..80381c5dcc 100644 --- a/src/Lucene.Net/Util/Packed/EliasFanoDecoder.cs +++ b/src/Lucene.Net/Util/Packed/EliasFanoDecoder.cs @@ -78,11 +78,11 @@ public virtual long CurrentIndex() { if (efIndex < 0) { - throw new InvalidOperationException("index before sequence"); + throw IllegalStateException.Create("index before sequence"); } if (efIndex >= numEncoded) { - throw new InvalidOperationException("index after sequence"); + throw IllegalStateException.Create("index after sequence"); } return efIndex; } diff --git a/src/Lucene.Net/Util/Packed/EliasFanoDocIdSet.cs b/src/Lucene.Net/Util/Packed/EliasFanoDocIdSet.cs index bf79801a1f..8e702c2c54 100644 --- a/src/Lucene.Net/Util/Packed/EliasFanoDocIdSet.cs +++ b/src/Lucene.Net/Util/Packed/EliasFanoDocIdSet.cs @@ -77,7 +77,7 @@ public override DocIdSetIterator GetIterator() { if (efEncoder.lastEncoded >= DocIdSetIterator.NO_MORE_DOCS) { - throw new NotSupportedException("Highest encoded value too high for DocIdSetIterator.NO_MORE_DOCS: " + efEncoder.lastEncoded); + throw UnsupportedOperationException.Create("Highest encoded value too high for DocIdSetIterator.NO_MORE_DOCS: " + efEncoder.lastEncoded); } return new DocIdSetIteratorAnonymousClass(this); } diff --git a/src/Lucene.Net/Util/Packed/EliasFanoEncoder.cs b/src/Lucene.Net/Util/Packed/EliasFanoEncoder.cs index 0d438c1a6e..929910997e 100644 --- a/src/Lucene.Net/Util/Packed/EliasFanoEncoder.cs +++ b/src/Lucene.Net/Util/Packed/EliasFanoEncoder.cs @@ -151,12 +151,12 @@ public EliasFanoEncoder(long numValues, long upperBound, long indexInterval) { if (numValues < 0L) { - throw new ArgumentException("numValues should not be negative: " + numValues); + throw new ArgumentOutOfRangeException(nameof(numValues), "numValues should not be negative: " + numValues); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.numValues = numValues; if ((numValues > 0L) && (upperBound < 0L)) { - throw new ArgumentException("upperBound should not be negative: " + upperBound + " when numValues > 0"); + throw new ArgumentOutOfRangeException(nameof(upperBound), "upperBound should not be negative: " + upperBound + " when numValues > 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.upperBound = numValues > 0 ? upperBound : -1L; // if there is no value, -1 is the best upper bound int nLowBits = 0; @@ -190,7 +190,7 @@ public EliasFanoEncoder(long numValues, long upperBound, long indexInterval) this.upperLongs = new long[(int)numLongsForHighBits]; if (indexInterval < 2) { - throw new ArgumentException("indexInterval should at least 2: " + indexInterval); + throw new ArgumentOutOfRangeException(nameof(indexInterval), "indexInterval should at least 2: " + indexInterval); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } // For the index: long maxHighValue = upperBound.TripleShift(this.numLowBits); @@ -230,7 +230,7 @@ private static long NumInt64sForBits(long numBits) // Note: int version in Fixed /// Call at most times to encode a non decreasing sequence of non negative numbers. /// The next number to be encoded. /// when called more than times. - /// when: + /// when: /// /// is smaller than an earlier encoded value, or /// is larger than . @@ -239,15 +239,15 @@ public virtual void EncodeNext(long x) { if (numEncoded >= numValues) { - throw new InvalidOperationException("encodeNext called more than " + numValues + " times."); + throw IllegalStateException.Create("EncodeNext() called more than " + numValues + " times."); } if (lastEncoded > x) { - throw new ArgumentException(x + " smaller than previous " + lastEncoded); + throw new ArgumentOutOfRangeException(nameof(x), x + " smaller than previous " + lastEncoded); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (x > upperBound) { - throw new ArgumentException(x + " larger than upperBound " + upperBound); + throw new ArgumentOutOfRangeException(nameof(x), x + " larger than upperBound " + upperBound); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } long highValue = x.TripleShift(numLowBits); EncodeUpperBits(highValue); diff --git a/src/Lucene.Net/Util/Packed/MonotonicBlockPackedReader.cs b/src/Lucene.Net/Util/Packed/MonotonicBlockPackedReader.cs index cca6ea47eb..ec225f8d90 100644 --- a/src/Lucene.Net/Util/Packed/MonotonicBlockPackedReader.cs +++ b/src/Lucene.Net/Util/Packed/MonotonicBlockPackedReader.cs @@ -2,6 +2,7 @@ using Lucene.Net.Diagnostics; using Lucene.Net.Store; using System; +using System.IO; namespace Lucene.Net.Util.Packed { @@ -54,7 +55,7 @@ public MonotonicBlockPackedReader(IndexInput @in, int packedIntsVersion, int blo int bitsPerValue = @in.ReadVInt32(); if (bitsPerValue > 64) { - throw new Exception("Corrupted"); + throw new IOException("Corrupted"); } if (bitsPerValue == 0) { diff --git a/src/Lucene.Net/Util/Packed/PackedInts.cs b/src/Lucene.Net/Util/Packed/PackedInts.cs index c2f36625d3..a908019738 100644 --- a/src/Lucene.Net/Util/Packed/PackedInts.cs +++ b/src/Lucene.Net/Util/Packed/PackedInts.cs @@ -80,11 +80,11 @@ public static void CheckVersion(int version) { if (version < VERSION_START) { - throw new ArgumentException("Version is too old, should be at least " + VERSION_START + " (got " + version + ")"); + throw new ArgumentOutOfRangeException(nameof(version), "Version is too old, should be at least " + VERSION_START + " (got " + version + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } else if (version > VERSION_CURRENT) { - throw new ArgumentException("Version is too new, should be at most " + VERSION_CURRENT + " (got " + version + ")"); + throw new ArgumentOutOfRangeException(nameof(version), "Version is too new, should be at most " + VERSION_CURRENT + " (got " + version + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } } @@ -965,7 +965,7 @@ public static Reader GetReaderNoHeader(DataInput @in, Format format, int version } else { - throw new InvalidOperationException("Unknown Writer format: " + format); + throw AssertionError.Create("Unknown Writer format: " + format); } } @@ -1094,7 +1094,7 @@ public static Reader GetDirectReaderNoHeader(IndexInput @in, Format format, int } else { - throw new InvalidOperationException("Unknwown format: " + format); + throw AssertionError.Create("Unknwown format: " + format); } } @@ -1121,9 +1121,9 @@ public override long Get(int index) { @in.Seek(endPointer); } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new InvalidOperationException("failed", e); + throw IllegalStateException.Create("failed", e); } } return result; @@ -1246,7 +1246,7 @@ public static Mutable GetMutable(int valueCount, int bitsPerValue, PackedInt32s. } else { - throw new InvalidOperationException(); + throw AssertionError.Create(); } } @@ -1354,7 +1354,7 @@ public static int BitsRequired(long maxValue) { if (maxValue < 0) { - throw new ArgumentException("maxValue must be non-negative (got: " + maxValue + ")"); + throw new ArgumentOutOfRangeException(nameof(maxValue), "maxValue must be non-negative (got: " + maxValue + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } return Math.Max(1, 64 - maxValue.LeadingZeroCount()); } diff --git a/src/Lucene.Net/Util/Packed/PackedReaderIterator.cs b/src/Lucene.Net/Util/Packed/PackedReaderIterator.cs index e87c020cf5..9425a17caa 100644 --- a/src/Lucene.Net/Util/Packed/PackedReaderIterator.cs +++ b/src/Lucene.Net/Util/Packed/PackedReaderIterator.cs @@ -75,7 +75,7 @@ public override Int64sRef Next(int count) int remaining = m_valueCount - position - 1; if (remaining <= 0) { - throw new EndOfStreamException(); + throw EOFException.Create(); } count = Math.Min(remaining, count); diff --git a/src/Lucene.Net/Util/Packed/PackedWriter.cs b/src/Lucene.Net/Util/Packed/PackedWriter.cs index bafb449a5a..4ff193dd33 100644 --- a/src/Lucene.Net/Util/Packed/PackedWriter.cs +++ b/src/Lucene.Net/Util/Packed/PackedWriter.cs @@ -62,7 +62,7 @@ public override void Add(long v) } if (m_valueCount != -1 && written >= m_valueCount) { - throw new EndOfStreamException("Writing past end of stream"); + throw EOFException.Create("Writing past end of stream"); } nextValues[off++] = v; if (off == nextValues.Length) diff --git a/src/Lucene.Net/Util/PagedBytes.cs b/src/Lucene.Net/Util/PagedBytes.cs index 6436e63ed6..1a562281f0 100644 --- a/src/Lucene.Net/Util/PagedBytes.cs +++ b/src/Lucene.Net/Util/PagedBytes.cs @@ -1,4 +1,4 @@ -using Lucene.Net.Diagnostics; +using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.Collections.Generic; @@ -244,11 +244,11 @@ public Reader Freeze(bool trim) { if (frozen) { - throw new InvalidOperationException("already frozen"); + throw IllegalStateException.Create("already frozen"); } if (didSkipBytes) { - throw new InvalidOperationException("cannot freeze when copy(BytesRef, BytesRef) was used"); + throw IllegalStateException.Create("cannot freeze when Copy(BytesRef, BytesRef) was used"); } if (trim && upto < blockSize) { @@ -294,6 +294,10 @@ public long RamBytesUsed() // TODO: this really needs to be refactored into fieldcacheimpl public long CopyUsingLengthPrefix(BytesRef bytes) { + // LUCENENET: Added guard clause for null + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (bytes.Length >= 32768) { throw new ArgumentException("max length is 32767 (got " + bytes.Length + ")"); @@ -497,7 +501,7 @@ public PagedBytesDataInput GetDataInput() { if (!frozen) { - throw new InvalidOperationException("must call Freeze() before GetDataInput()"); + throw IllegalStateException.Create("must call Freeze() before GetDataInput()"); } return new PagedBytesDataInput(this); } @@ -513,7 +517,7 @@ public PagedBytesDataOutput GetDataOutput() { if (frozen) { - throw new InvalidOperationException("cannot get DataOutput after Freeze()"); + throw IllegalStateException.Create("cannot get DataOutput after Freeze()"); } return new PagedBytesDataOutput(this); } diff --git a/src/Lucene.Net/Util/PriorityQueue.cs b/src/Lucene.Net/Util/PriorityQueue.cs index f331ae2d1e..e03768cbdc 100644 --- a/src/Lucene.Net/Util/PriorityQueue.cs +++ b/src/Lucene.Net/Util/PriorityQueue.cs @@ -72,7 +72,7 @@ protected PriorityQueue(int maxSize, bool prepopulate) // LUCENENET specific - m // one will actually insert this many objects into // the PQ: // Throw exception to prevent confusing OOME: - throw new ArgumentException("maxSize must be <= " + ArrayUtil.MAX_ARRAY_LENGTH + "; got: " + maxSize); + throw new ArgumentOutOfRangeException(nameof(maxSize), "maxSize must be <= " + ArrayUtil.MAX_ARRAY_LENGTH + "; got: " + maxSize); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } else { diff --git a/src/Lucene.Net/Util/QueryBuilder.cs b/src/Lucene.Net/Util/QueryBuilder.cs index 85905b6fa5..86de3fee62 100644 --- a/src/Lucene.Net/Util/QueryBuilder.cs +++ b/src/Lucene.Net/Util/QueryBuilder.cs @@ -1,4 +1,4 @@ -using J2N.Collections.Generic.Extensions; +using J2N.Collections.Generic.Extensions; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Diagnostics; using System; @@ -237,15 +237,15 @@ protected Query CreateFieldQuery(Analyzer analyzer, Occur @operator, string fiel hasMoreTokens = buffer.IncrementToken(); } } - catch (IOException) + catch (Exception e) when (e.IsIOException()) { // ignore } } } - catch (IOException e) + catch (Exception e) when (e.IsIOException()) { - throw new Exception("Error analyzing query text", e); + throw RuntimeException.Create("Error analyzing query text", e); } finally { @@ -269,7 +269,7 @@ protected Query CreateFieldQuery(Analyzer analyzer, Occur @operator, string fiel if (Debugging.AssertsEnabled) Debugging.Assert(hasNext == true); termAtt.FillBytesRef(); } - catch (IOException) + catch (Exception e) when (e.IsIOException()) { // safe to ignore, because we know the number of tokens } @@ -295,7 +295,7 @@ protected Query CreateFieldQuery(Analyzer analyzer, Occur @operator, string fiel if (Debugging.AssertsEnabled) Debugging.Assert(hasNext == true); termAtt.FillBytesRef(); } - catch (IOException) + catch (Exception e) when (e.IsIOException()) { // safe to ignore, because we know the number of tokens } @@ -317,7 +317,7 @@ protected Query CreateFieldQuery(Analyzer analyzer, Occur @operator, string fiel if (Debugging.AssertsEnabled) Debugging.Assert(hasNext == true); termAtt.FillBytesRef(); } - catch (IOException) + catch (Exception e) when (e.IsIOException()) { // safe to ignore, because we know the number of tokens } @@ -364,7 +364,7 @@ protected Query CreateFieldQuery(Analyzer analyzer, Occur @operator, string fiel positionIncrement = posIncrAtt.PositionIncrement; } } - catch (IOException) + catch (Exception e) when (e.IsIOException()) { // safe to ignore, because we know the number of tokens } @@ -415,7 +415,7 @@ protected Query CreateFieldQuery(Analyzer analyzer, Occur @operator, string fiel positionIncrement = posIncrAtt.PositionIncrement; } } - catch (IOException) + catch (Exception e) when (e.IsIOException()) { // safe to ignore, because we know the number of tokens } diff --git a/src/Lucene.Net/Util/RamUsageEstimator.cs b/src/Lucene.Net/Util/RamUsageEstimator.cs index 697d263c1d..8cabaa33a6 100644 --- a/src/Lucene.Net/Util/RamUsageEstimator.cs +++ b/src/Lucene.Net/Util/RamUsageEstimator.cs @@ -439,6 +439,10 @@ public static long ShallowSizeOf(object obj) /// if is an array class. public static long ShallowSizeOfInstance(Type clazz) { + // LUCENENET: Added guard clause for null + if (clazz is null) + throw new ArgumentNullException(nameof(clazz)); + if (clazz.IsArray) { throw new ArgumentException("this method does not work with array classes."); @@ -587,10 +591,10 @@ private static long MeasureObjectSize(object root) totalSize += cachedInfo.AlignedShallowInstanceSize; } - catch (Exception e) + catch (Exception e) when (e.IsIllegalAccessException()) { // this should never happen as we enabled setAccessible(). - throw new Exception("Reflective field access failed?", e); + throw RuntimeException.Create("Reflective field access failed?", e); } } } @@ -665,7 +669,7 @@ private static long AdjustForField(long sizeSoFar, FieldInfo f) // } // catch (Exception ex) // { - // throw new Exception("Access problem with sun.misc.Unsafe", ex); + // throw RuntimeException.Create("Access problem with sun.misc.Unsafe", ex); // } //} //else @@ -1032,7 +1036,7 @@ private object FetchNext() public void Reset() { - throw new NotSupportedException(); + throw UnsupportedOperationException.Create(); } public void Dispose() diff --git a/src/Lucene.Net/Util/RefCount.cs b/src/Lucene.Net/Util/RefCount.cs index 9750997fe5..c02f440562 100644 --- a/src/Lucene.Net/Util/RefCount.cs +++ b/src/Lucene.Net/Util/RefCount.cs @@ -71,7 +71,7 @@ public void DecRef() } else if (rc < 0) { - throw new InvalidOperationException("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/Util/SPIClassIterator.cs b/src/Lucene.Net/Util/SPIClassIterator.cs index 1829817329..30babe3812 100644 --- a/src/Lucene.Net/Util/SPIClassIterator.cs +++ b/src/Lucene.Net/Util/SPIClassIterator.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; @@ -97,7 +97,6 @@ private static JCG.HashSet LoadTypes() // LUCENENET: Avoid static construc types.Add(type); } } -#pragma warning disable CA1031 // Do not catch general exception types catch { // swallow @@ -108,7 +107,6 @@ private static JCG.HashSet LoadTypes() // LUCENENET: Avoid static construc { // swallow } -#pragma warning restore CA1031 // Do not catch general exception types } return types; } @@ -137,144 +135,4 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() return GetEnumerator(); } } - - /* Being Re-written - public sealed class SPIClassIterator : IEnumerator - { - private const string META_INF_SERVICES = "META-INF/services/"; - - private readonly Type Clazz; - private readonly ClassLoader Loader; - private readonly IEnumerator ProfilesEnum; - private IEnumerator LinesIterator; - - public static SPIClassIterator Get(Type clazz) - { - return new SPIClassIterator(clazz, Thread.CurrentThread.ContextClassLoader); - } - - public static SPIClassIterator Get(Type clazz, ClassLoader loader) - { - return new SPIClassIterator(clazz, loader); - } - - /// - /// Utility method to check if some class loader is a (grand-)parent of or the same as another one. - /// this means the child will be able to load all classes from the parent, too. - /// - public static bool IsParentClassLoader(ClassLoader parent, ClassLoader child) - { - while (child != null) - { - if (child == parent) - { - return true; - } - child = child.Parent; - } - return false; - } - - private SPIClassIterator(Type clazz, ClassLoader loader) - { - this.Clazz = clazz; - try - { - string fullName = META_INF_SERVICES + clazz.Name; - this.ProfilesEnum = (loader == null) ? ClassLoader.getSystemResources(fullName) : loader.getResources(fullName); - } - catch (IOException ioe) - { - throw new ServiceConfigurationError("Error loading SPI profiles for type " + clazz.Name + " from classpath", ioe); - } - this.Loader = (loader == null) ? ClassLoader.SystemClassLoader : loader; - this.LinesIterator = Collections.emptySet().GetEnumerator(); - } - - private bool LoadNextProfile() - { - List lines = null; - while (ProfilesEnum.MoveNext()) - { - if (lines != null) - { - lines.Clear(); - } - else - { - lines = new List(); - } - URL url = ProfilesEnum.Current; - try - { - InputStream @in = url.openStream(); - IOException priorE = null; - try - { - BufferedReader reader = new BufferedReader(new InputStreamReader(@in, IOUtils.CHARSET_UTF_8)); - string line; - while ((line = reader.readLine()) != null) - { - int pos = line.IndexOf('#'); - if (pos >= 0) - { - line = line.Substring(0, pos); - } - line = line.Trim(); - if (line.Length > 0) - { - lines.Add(line); - } - } - } - catch (IOException ioe) - { - priorE = ioe; - } - finally - { - IOUtils.CloseWhileHandlingException(priorE, @in); - } - } - catch (IOException ioe) - { - throw new ServiceConfigurationError("Error loading SPI class list from URL: " + url, ioe); - } - if (lines.Count > 0) - { - this.LinesIterator = lines.GetEnumerator(); - return true; - } - } - return false; - } - - public override bool HasNext() - { - } - - public override Type Next() - { - // hasNext() implicitely loads the next profile, so it is essential to call this here! - if (!HasNext()) - { - throw new NoSuchElementException(); - } - string c = LinesIterator.next(); - try - { - // don't initialize the class (pass false as 2nd parameter): - return Type.GetType(c, false, Loader).asSubclass(Clazz); - } - catch (ClassNotFoundException cnfe) - { - throw new ServiceConfigurationError(string.format(Locale.ROOT, "A SPI class of type %s with classname %s does not exist, " + "please fix the file '%s%1$s' in your classpath.", Clazz.Name, c, META_INF_SERVICES)); - } - } - - public override void Remove() - { - throw new NotSupportedException(); - } - }*/ } \ No newline at end of file diff --git a/src/Lucene.Net/Util/UnicodeUtil.cs b/src/Lucene.Net/Util/UnicodeUtil.cs index 663fcc00e5..23b1493dbe 100644 --- a/src/Lucene.Net/Util/UnicodeUtil.cs +++ b/src/Lucene.Net/Util/UnicodeUtil.cs @@ -1,4 +1,4 @@ -using J2N; +using J2N; using J2N.Text; using Lucene.Net.Diagnostics; using System; @@ -347,7 +347,7 @@ private static boolean matches(char[] source, int offset, int length, byte[] res return false; } return s1.equals(s2, StringComparison.Ordinal); - } catch (UnsupportedEncodingException uee) { + } catch (Exception uee) when (uee.IsUnsupportedEncodingException()) { return false; } } @@ -375,7 +375,7 @@ private static boolean matches(String source, int offset, int length, byte[] res return false; } return s1.equals(s2, StringComparison.Ordinal); - } catch (UnsupportedEncodingException uee) { + } catch (Exception uee) when (uee.IsUnsupportedEncodingException()) { return false; } } @@ -593,7 +593,7 @@ public static int CodePointCount(BytesRef utf8) } // Anything not covered above is invalid UTF8. - throw new ArgumentException(); + throw new ArgumentException("Invalid UTF-8"); } // Check if we didn't go over the limit on the last character. @@ -721,7 +721,7 @@ public static char[] ToCharArray(int[] codePoints, int offset, int count) { if (count < 0) { - throw new ArgumentException(); + throw new ArgumentOutOfRangeException(nameof(count), "count must be >= 0"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } int countThreashold = 1024; // If the number of chars exceeds this, we count them instead of allocating count * 2 // LUCENENET: as a first approximation, assume each codepoint diff --git a/src/Lucene.Net/Util/VirtualMethod.cs b/src/Lucene.Net/Util/VirtualMethod.cs index c294037fcc..f91b10bf6c 100644 --- a/src/Lucene.Net/Util/VirtualMethod.cs +++ b/src/Lucene.Net/Util/VirtualMethod.cs @@ -131,10 +131,10 @@ public VirtualMethod(Type baseClass, string method, params Type[] parameters) } else if (!singletonSet.Add(mi)) { - throw new NotSupportedException("VirtualMethod instances must be singletons and therefore " + "assigned to static final members in the same class, they use as baseClass ctor param."); + throw UnsupportedOperationException.Create("VirtualMethod instances must be singletons and therefore " + "assigned to static final members in the same class, they use as baseClass ctor param."); } } - catch (NotSupportedException nsme) + catch (Exception nsme) when (nsme.IsNoSuchMethodException()) { throw new ArgumentException(baseClass.Name + " has no such method: " + nsme.Message, nsme); } @@ -174,12 +174,21 @@ private int ReflectImplementationDistance(Type subclazz) // lookup method, if success mark as overridden if (!overridden) { - MethodInfo mi = GetMethod(clazz, method, - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly, - parameters); - - if (mi != null) - overridden = true; + try + { + MethodInfo mi = GetMethod(clazz, method, + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly, + parameters); + + // LUCENENET specific - .NET returns null when it cannot find a method, it doesn't throw an exception + if (mi != null) + overridden = true; + } + // LUCENENET specific - there is a minor chance this will happen in .NET. This is + // just to mimic the fact they were swallowing in Java when the method isn't found. + catch (AmbiguousMatchException) + { + } } // increment distance if overridden diff --git a/src/Lucene.Net/Util/WAH8DocIdSet.cs b/src/Lucene.Net/Util/WAH8DocIdSet.cs index b9455e247d..ab832b923a 100644 --- a/src/Lucene.Net/Util/WAH8DocIdSet.cs +++ b/src/Lucene.Net/Util/WAH8DocIdSet.cs @@ -118,6 +118,10 @@ public static WAH8DocIdSet Intersect(ICollection docIdSets) /// public static WAH8DocIdSet Intersect(ICollection docIdSets, int indexInterval) { + // LUCENENET: Added guard clause for null + if (docIdSets is null) + throw new ArgumentNullException(nameof(docIdSets)); + switch (docIdSets.Count) { case 0: @@ -298,7 +302,7 @@ public virtual object SetIndexInterval(int indexInterval) { if (indexInterval < MIN_INDEX_INTERVAL) { - throw new ArgumentException("indexInterval must be >= " + MIN_INDEX_INTERVAL); + throw new ArgumentOutOfRangeException(nameof(indexInterval), "indexInterval must be >= " + MIN_INDEX_INTERVAL); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } this.indexInterval = indexInterval; return this; @@ -353,9 +357,9 @@ internal virtual void WriteSequence() { WriteHeader(reverse, clean, dirtyWords.Length); } - catch (IOException cannotHappen) + catch (Exception cannotHappen) when (cannotHappen.IsIOException()) { - throw new InvalidOperationException(cannotHappen.ToString(), cannotHappen); // LUCENENET NOTE: This was AssertionError in Lucene + throw AssertionError.Create(cannotHappen.Message, cannotHappen); } @out.WriteBytes(dirtyWords.Bytes, 0, dirtyWords.Length); dirtyWords.Length = 0; @@ -535,7 +539,7 @@ public Builder Add(int docID) { if (docID <= lastDocID) { - throw new ArgumentException("Doc ids must be added in-order, got " + docID + " which is <= lastDocID=" + lastDocID); + throw new ArgumentOutOfRangeException(nameof(docID), "Doc ids must be added in-order, got " + docID + " which is <= lastDocID=" + lastDocID); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } int wordNum = WordNum(docID); if (this.wordNum == -1) diff --git a/src/dotnet/Lucene.Net.Tests.ICU/Search/PostingsHighlight/TestICUPostingsHighlighter.cs b/src/dotnet/Lucene.Net.Tests.ICU/Search/PostingsHighlight/TestICUPostingsHighlighter.cs index 1c15d4d70e..27415e1ad0 100644 --- a/src/dotnet/Lucene.Net.Tests.ICU/Search/PostingsHighlight/TestICUPostingsHighlighter.cs +++ b/src/dotnet/Lucene.Net.Tests.ICU/Search/PostingsHighlight/TestICUPostingsHighlighter.cs @@ -430,9 +430,7 @@ public void TestUserFailedToIndexOffsets() highlighter.Highlight("body", query, searcher, topDocs, 2); fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected } @@ -442,9 +440,7 @@ public void TestUserFailedToIndexOffsets() highlighter.Highlight("title", new TermQuery(new Term("title", "test")), searcher, topDocs, 2); fail("did not hit expected exception"); } -#pragma warning disable 168 - catch (ArgumentException iae) -#pragma warning restore 168 + catch (Exception iae) when (iae.IsIllegalArgumentException()) { // expected }