I'm writing a custom class in C# and I'm throwing a couple exceptions if people give the wrong inputs in some of the methods. If the exception is thrown, will any of the code in the method after the throw still be executed? Do I have to put a break after the throw, or does a throw always quit the method?
It does, yes.
After throwing an exception, you do not need to return because throw returns for you. Throwing will bubble up the call stack to the next exception handler so returning is not required.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred.
One way to execute the loop without breaking is to move the code that causes the exception to another method that handles the exception. If you have try catch within the loop it gets executed completely inspite of exceptions.
When you throw an exception, the next code to get executed is any catch block that covers that throw within the method (if any) then, the finally block (if any). You can have a try, a try-catch, a try-catch-finally or a try-finally. Then, if the exception is not handled, re-thrown by a catch block or not caught at all, control is returned to the caller. For example, you will get "Yes1, Yes2, Yes3" from this code ...
try { Console.WriteLine("Yes1"); throw (new Exception()); Console.WriteLine("No1"); } catch { Console.WriteLine("Yes2"); throw; Console.WriteLine("No2"); } finally { Console.WriteLine("Yes3"); } Console.WriteLine("No3");
Throw will move up the stack, thus exiting the method.
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