Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to break after throwing exception?

Tags:

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?

like image 222
Ross Avatar asked Jun 13 '09 06:06

Ross


People also ask

Does throwing exception break function?

It does, yes.

Do you need to return after throwing an exception?

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.

What happens after throwing an exception?

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.

How do you throw an exception without breaking the loop?

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.


2 Answers

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"); 
like image 165
JP Alioto Avatar answered Sep 30 '22 20:09

JP Alioto


Throw will move up the stack, thus exiting the method.

like image 35
Jarrett Widman Avatar answered Sep 30 '22 20:09

Jarrett Widman