Marking a method as one that throws Exceptions

Topics: C# Language Design
Mar 15, 2015 at 4:44 PM
Frequently we have code such as the below
        static int GetSomething()
        {
            try
            {
                return 0;
            }
            catch (Exception e)
            {
                DetermineSpecificExceptionToThrow(e);
            }
        }

        static void DetermineSpecificExceptionToThrow(Exception exception)
        {
            // lot of logic here to determine which exception should be thrown
            // This is typically done when you're throwing specific business exceptions
            // while this exception is the inner exception
            // based upon some information/data in the original exception           
        }
The compiler gives an error CS0161. One option is to have the Determine...... method throw exceptions. However, there are time when you don't want to (or can't) do that.

Further the Unit testing code coverage tool doesn't see this correctly (say we did something similar in a switch case statement.

If we could mark a method as one that throws an exception (with an attribute such as [throws]). This would help in both scenarios. Of course the compiler can ensure that all code paths throw an exception in these methods.
Mar 16, 2015 at 12:01 PM
Why not return an exception from the Determine function and throw it in the catch branch?
 catch (Exception e)
 {
      throw DetermineSpecificExceptionToThrow(e);
 }

static Exception DetermineSpecificExceptionToThrow(Exception exception)
Mar 16, 2015 at 12:05 PM
Edited Mar 16, 2015 at 12:09 PM
Do that today. There are many cases where this is not the best approach.

FYI - I'm not looking for alternatives (since I already know of them). I'm asking specifically for a feature.

This thread has been moved here (Where there is a similar request)
[Add Never type and support for methods that cannot return](https://github.com/dotnet/roslyn/issues/1226