Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does execution resume following an exception?

In general, where does program execution resume after an exception has been thrown and caught? Does it resume following the line of code where the exception was thrown, or does it resume following where it's caught? Also, is this behavior consistent across most programming languages?

like image 828
theactiveactor Avatar asked Dec 25 '09 13:12

theactiveactor


2 Answers

The code inside the catch block is executed and the original execution continues right after the catch block.

like image 142
Moshe Levi Avatar answered Oct 04 '22 01:10

Moshe Levi


the execution resumes where the exception is caught, that is at the beginning of the catch block which specifically address the current exception type. the catch block is executed, the other catch blocks are ignored (think of multiple catch block as a switch statement). in some languages, a finally block may also be executed after the catch. then the program proceed with the next instruction following the whole try ... catch ... finally ....

you should note that if an exception is not caught in a block, the exception is propagated to the caller of the current function, and up the call stack until a catch processes the exception. in this case, you can think of function calls like a macro: insert the code of each function where it is called, and you will clearly see the nesting of every try .. catch ... finally ... blocks.

if there is no handler for an exception, the program generally crashes. (some languages may be different on this point).

the behavior for the execution flow is consistent accross every languages i know. the only difference lies in the try ... catch ... finally ... construct: the finally does not exists in every language, some languages does not allow a finally and a catch in the same block (you have to nest two try to use the 2), some languages allows to catch everything (the catch (...) in C++) while some languages don't.

like image 34
Adrien Plisson Avatar answered Oct 04 '22 02:10

Adrien Plisson