Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does throwing an exception within a method cause the method to return?

I have the following code:

public static Point operator /(Point point, double value)
    {
        if (value == 0)
        {
            throw new DivideByZeroException("Cannot divide by zero");
            return Point.Origin;
        }
        return new Point(point.X / value, point.Y / value, point.Z / value);
    }

And the first return statement (return Point.Origin;) is underlined in green in Visual Studio. The message says "Unreachable code detected" when the cursor is hovered over the underlined text. This leads me to my question stated in the title line:

Does throwing an exception within a method cause the method to return?

like image 312
Jackson Dean Goodwin Avatar asked Jan 14 '13 17:01

Jackson Dean Goodwin


1 Answers

Well, it causes the execution of the method to exit, yes. The exception is thrown up the stack, to the closest method which catches it. If it didn't affect execution flow, it would be pretty pointless.

This isn't the same as the method returning "normally" - i.e. without an exception. So suppose the calling method had:

Point foo = bar / baz;
Console.WriteLine("Done");

In this case the Console.WriteLine() call wouldn't execute if the division operator threw an exception. Instead, either the exception would be caught in this method, or the exception would propagate to that method's caller, etc.

(finally blocks will be executed along the way too.)

It's probably worth reading the MSDN guide to "handling and throwing exceptions".

like image 132
Jon Skeet Avatar answered Sep 23 '22 15:09

Jon Skeet