|
Try, Catch & Finally
Typical questions: What would happen if my exception handling block looks like following:
try{
...
}finally{
...
}catch(){
...
}
OR
try{
...
}finally{
...
}finally{
...
}
Questions could be many.
To get the right answer, keep following things in mind:
- If all of Try, Catch & Finally are present, then they must appear in this order only.
- Try cannot exist alone. There must be a catch or finally.
- Nothing amongst try, catch & finally can come after finally block (not even another finally). If there exists a try after finally, then it would be a different exception handling scenario; i.e. either it would be inside finally block OR it would be a new try block.
- In case of nested exception handling block, all rules mentioned above would be applicable to inner blocks as well.
Some more points:
- Catch blocks are executed in the order they appear.
- Finally is executed even when a method is about to return to due to an explicit return. In other words, if there is a return statement before finally, then also the finally would be executed just before exiting the method.
This also means that if there are two return statements: one before finally & one inside finally; the one inside finally would be executed in the end.
- Try Catch block can not be used for branching; i.e. code would not "return" to "try" block, because an exception does not result in "catch" block being "called". Instead, when an exception occurs inside try block, the control shifts to catch block.
|