Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do I need a return after throwing exception (c++ and c#)

Tags:

c++

c#

exception

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#?

like image 620
mans Avatar asked May 31 '13 09:05

mans


People also ask

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.

Is throwing an exception the same as returning a value?

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.

What happens after an exception is thrown in C++?

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.


2 Answers

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.)

like image 168
Aasmund Eldhuset Avatar answered Sep 21 '22 06:09

Aasmund Eldhuset


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.

like image 21
Quinton Bernhardt Avatar answered Sep 21 '22 06:09

Quinton Bernhardt