Fix MA0054 false negative on exceptions of a derived type

Merged
ME
2mo ago
+125-2

What

MA0054 only reports throw new System.Exception(...). For any other exception type, the operand of the throw is an implicit conversion to System.Exception around the object creation, so the operation.Exception is IObjectCreationOperation check never matches:

try { }
catch (System.Exception ex)
{
    throw new System.InvalidOperationException("m"); // expected: MA0054, actual: no diagnostic
}

The code fix also has a bug that this change exposes. When the constructor call uses named arguments that are not in parameter order, the fix inserts a positional argument after them, which doesn't compile:

throw new System.ArgumentException(paramName: "p", message: "m");
// fixed to: new System.ArgumentException(paramName: "p", message: "m", ex) -> CS8323

Fix

  • Analyzer: the rule removes the implicit conversions from the thrown expression before it checks for an object creation. This covers throw statements and throw expressions.
  • Code fix: when the argument list already contains a named argument, the fix appends a named argument (innerException: ex). Before, it did this only when the insertion index was past the end of the argument list.
  • The MA0054 docs now have an example with a derived exception type.

Note: this fixes a false negative, so projects that throw a derived exception from a catch block without the inner exception will get new MA0054 warnings. The docs already describe that case.

Tests

  • Added InCaughtExceptionWithoutInnerException_DerivedException_CodeFix, InCaughtExceptionWithoutInnerException_ThrowExpression_CodeFix and InCaughtExceptionWithoutInnerException_NamedArgumentsOutOfOrder_CodeFix. All 3 failed before the fix, and the named-arguments test still failed with only the analyzer change.
  • Ran EmbedCaughtExceptionAsInnerExceptionAnalyzerTests on roslyn5.9 and roslyn4.8: 8/8 passed on each.