How can we easily find which line in the code throws an exception at runtime?

Consider the following analyzer:

public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
    var throwStatement = node as ThrowStatementSyntax;

    var isObjectCreationExpression = throwStatement.Expression is ObjectCreationExpressionSyntax;
    var obj = throwStatement.Expression as ObjectCreationExpressionSyntax;

    var isCorrectTypeOfExpression = (obj.Type as IdentifierNameSyntax).Identifier.Text == typeof(ArgumentException).Name;
}

C SyntaxKind.ThrowStatementas a kind of interest.

objshould be nullif the specified exception was not declared there, in the form new Exception(), but rather presented as throw ewhere ethe previously declared exception is.

This, in turn, will trigger NullReferenceExceptionwhen obj.Typecalled immediately after.

The example in question:

static void Method1()
{
    throw new ArgumentException();
}

static void Method2(ArgumentException e)
{
    throw e;
}

The first one throwwill only pass the analyzer in a fine, but the second will call objhow null, since it has no type ObjectCreationExpressionSyntax.

In Visual Studio Visual Studio, this will display as an informational message:

"FormattingFixes.EmptyArgumentException.ArgumentExceptionAnalyzer" " ​​ ".

, , . 1, .

"" , . - , , , , , 2.

, ?

+4
2

, , :

"" "". "" " ". NullReferenceException Find, "throw". , VS , NullReferenceException. , , .

, "" > "", "", "" " ". , , VS, . ( , .)

, , /, .

:

var isCorrectTypeOfExpression = (obj.Type as IdentifierNameSyntax).Identifier.Text == typeof(ArgumentException).Name;

- , throw new System.ArgumentException()? , ObjectCreationExpression, , . ( , , .)

+5

, , .

  • StackTrace .
  • .
  • .

.

try
{

    //TODO
    throw new Exception();
}
catch (Exception ex)
{
    var stacktrace = new StackTrace(ex, true);
    var frame = st.GetFrame(0);
    var filelinenumber = frame.GetFileLineNumber();
}
-1

Source: https://habr.com/ru/post/1536665/


All Articles