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

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


Solution 1:

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

Solution 2:

No, you don't need to return, because after the exception is thrown the code after that wont' be executed.

Solution 3:

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.