I have a function that generate an exception. For example the following code:
void test() { ifstream test("c:/afile.txt"); if(!test) { throw exception("can not open file"); } // other section of code that reads from file. }
Do I need a return after throwing the exception?
What is the case in c#?
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.
It's not possible to both throw an exception and return a value from a single function call. Perhaps it does something like returning false if there's an error, but throwing an exception if the input is invalid.
In the C++ exception mechanism, control moves from the throw statement to the first catch statement that can handle the thrown type. When the catch statement is reached, all of the automatic variables that are in scope between the throw and catch statements are destroyed in a process that is known as stack unwinding.
throw
usually causes the function to terminate immediately, so you even if you do put any code after it (inside the same block), it won't execute. This goes for both C++ and C#. However, if you throw an exception inside a try
block and the exception gets caught, execution will continue in the appropriate catch
block, and if there is a finally
block (C# only), it will be executed whether an exception is thrown or not. At any rate, any code immediately after the throw
will never be executed.
(Note that having a throw
directly inside a try
/catch
is usually a design problem - exceptions are designed for bubbling errors up across functions, not for error handling within a function.)
Strictly speaking throwing will NOT necessarily terminate the function immediately always.... as in this case,
try { throw new ApplicationException(); } catch (ApplicationException ex) { // if not re-thrown, function will continue as normal after the try/catch block } catch (Exception ex) { }
and then there is the Finally block - but after that it will exit.
So no, you do not have to return.
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