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?
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With