Could possibly call to method annotated with [DoesNotReturn] spare you writing return statement? #7071
-
Following code: public static async Task<T> InvokeWithTargetInvocationExceptionUnpacking<T>(
this MethodInfo methodInfo,
object? instance,
object[] parameters)
{
var task = (Task<T>)(methodInfo.Invoke(instance, parameters)
?? throw new InvalidOperationException("Method returned null object"));
try
{
return await task;
}
catch (TargetInvocationException exception) when (exception.InnerException != null)
{
ExceptionDispatchInfo.Capture(exception.InnerException).Throw();
}
} produces compilation error CS0161: not all code paths return a value.
Putting [DoesNotReturn] attribute on method that will return is forbidden with compilation error. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Because |
Beta Was this translation helpful? Give feedback.
-
Is there some specific reason the API is designed to "wrap" the throw statement, when it is intended to be called within catch blocks? The main reason I'm aware of to wrap throw statements in this way is to make it so your method can still be inlined. But that's already not going to happen in a method with a try/catch, I think. |
Beta Was this translation helpful? Give feedback.
Because
DoesNotReturn
isn't actually a contract. It can trivially be violated. However, the compiler 'reachability analysis' is precise and depends only on things it can prove. As it cannot prove that DoesNotReturn is true, it must error.