Search code examples
c#.netexceptionattributes

How to mark a method will throw unconditionally?


Is there a way to decorate a method that will do some logging, then throw an exception unconditionally, as such?

I have code like this:

void foo(out int x)
{
  if( condition() ) { x = bar(); return; }

  // notice that x is not yet set here, but compiler doesn't complain

  throw new Exception( "missed something." );
}

If I try writing it like this I get a problem:

void foo(out int x)
{
  if( condition() ) { x = bar(); return; }

  // compiler complains about x not being set yet

  MyMethodThatAlwaysThrowsAnException( "missed something." );
}

Any suggestions? Thanks.


Solution

  • To mark method as always throwing you can use [DoesNotReturn] attribute.

    Attribute reference: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.doesnotreturnattribute?view=net-6.0

    Usage description: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis#stop-nullable-analysis-when-called-method-throws