Skip to content

Commit

Permalink
SWEEP: Reviewed all catch blocks where Lucene uses ParseException and…
Browse files Browse the repository at this point in the history
… converted them to use our IsParseException() extension method (see apache#446).
  • Loading branch information
NightOwl888 committed Apr 14, 2021
1 parent acc5391 commit 9ae07ac
Show file tree
Hide file tree
Showing 21 changed files with 84 additions and 88 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -144,14 +144,14 @@ public override bool Accept(AttributeSource source)
m_termAtt = source.AddAttribute<ICharTermAttribute>();
}

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 _);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ public override void Parse(TextReader @in)
}
catch (Exception e) when (e.IsIllegalArgumentException())
{
throw new Exception("Invalid synonym rule at line " + lineNumber, e);
throw new FormatException("Invalid synonym rule at line " + lineNumber, e);
//ex.initCause(e);
//throw ex;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public override void Parse(TextReader @in)
}
catch (Exception e) when (e.IsIllegalArgumentException())
{
throw new Exception("Invalid synonym rule at line " + lineNumber.ToString(), e);
throw new FormatException("Invalid synonym rule at line " + lineNumber.ToString(), e);
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
6 changes: 3 additions & 3 deletions src/Lucene.Net.Benchmark/ByTask/Tasks/AnalyzerFactoryTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public override void SetParams(string @params)
{
intArgValue = int.Parse(argValue, CultureInfo.InvariantCulture);
}
catch (FormatException e)
catch (Exception e) when (e.IsParseException())
{
throw new Exception
("Line #" + GetLineNumber(stok) + ": Exception parsing " + argName + " value '" + argValue + "'", e);
Expand Down Expand Up @@ -204,7 +204,7 @@ public override void SetParams(string @params)
{
intArgValue = int.Parse(argValue, CultureInfo.InvariantCulture);
}
catch (FormatException e)
catch (Exception e) when (e.IsParseException())
{
throw new Exception
("Line #" + GetLineNumber(stok) + ": Exception parsing " + argName + " value '" + argValue + "'", e);
Expand Down Expand Up @@ -257,7 +257,7 @@ public override void SetParams(string @params)
{
intArgValue = int.Parse(stok.StringValue.Trim(), CultureInfo.InvariantCulture);
}
catch (FormatException e)
catch (Exception e) when (e.IsParseException())
{
throw new Exception
("Line #" + GetLineNumber(stok) + ": Exception parsing " + argName + " value '" + stok.StringValue + "'", e);
Expand Down
2 changes: 1 addition & 1 deletion src/Lucene.Net.Benchmark/Quality/QualityQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.IsParseException())
{
// fall back to string comparison
return queryID.CompareToOrdinal(other.queryID);
Expand Down
17 changes: 7 additions & 10 deletions src/Lucene.Net.Codecs/SimpleText/SimpleTextDocValuesReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -413,7 +411,7 @@ 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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
35 changes: 1 addition & 34 deletions src/Lucene.Net.Expressions/JS/JavascriptLexer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,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);
}

// delegates
Expand Down Expand Up @@ -2178,35 +2176,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)
{
}

// LUCENENET: For testing purposes
internal ParseException(string message)
: base(message)
{
}

#if FEATURE_SERIALIZABLE_EXCEPTIONS
/// <summary>
/// Initializes a new instance of this class with serialized data.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
protected ParseException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
}
6 changes: 2 additions & 4 deletions src/Lucene.Net.Expressions/JS/JavascriptParser.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
Expand Down Expand Up @@ -205,9 +205,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);
}

public static string GetReadableTokenString(IToken token)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ 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) when (tme.IsError())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
{
number = numberFormat.Parse(text);
}
catch (FormatException e)
catch (Exception e) when (e.IsParseException())
{
throw new QueryNodeParseException(new Message(
QueryParserMessages.COULD_NOT_PARSE_NUMBER, fieldNode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
{
lowerNumber = numberFormat.Parse(lowerText);
}
catch (FormatException e)
catch (Exception e) when (e.IsParseException())
{
throw new QueryNodeParseException(new Message(
QueryParserMessages.COULD_NOT_PARSE_NUMBER, lower
Expand All @@ -101,7 +101,7 @@ protected override IQueryNode PostProcessNode(IQueryNode node)
{
upperNumber = numberFormat.Parse(upperText);
}
catch (FormatException e)
catch (Exception e) when (e.IsParseException())
{
throw new QueryNodeParseException(new Message(
QueryParserMessages.COULD_NOT_PARSE_NUMBER, upper
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Lucene.Net.Suggest/Suggest/FileDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ internal void ReadWeight(string weight)
}
catch (FormatException e)
{
// LUCENENET TODO: This is just so we can see what string and what culture was being tested when parsing failed,
// LUCENENET: 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);
}
Expand Down
13 changes: 4 additions & 9 deletions src/Lucene.Net.TestFramework/Search/CheckHits.cs
Original file line number Diff line number Diff line change
Expand Up @@ -400,21 +400,16 @@ 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.
if (float.TryParse(descr.Substring(k1, k2 - k1).Trim(), out x))
{
// 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
{
}
}
}
// TODO: this is a TERRIBLE assertion!!!!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading

0 comments on commit 9ae07ac

Please sign in to comment.