The finally Keyword Catching Exceptions

J.E.D.I. } What is the output of this program when tested on the following arguments? a No argument b 15 c 15 3 d 15 0 The expected output for NestedTryDemo2 is similar to that of NestedTryDemo.

2.3.2 The finally Keyword

Finally, you’ll now incorporate the finally keyword to try-catch statements Here is how this reserved word fits in: try { code to be monitored for exceptions } catch ExceptionType1 ObjName { handler if ExceptionType1 occurs } ... } finally { code to be executed before the try block ends } Coding Guidelines: Again, same coding convention applies to the finally block as in the catch block. It starts after the close curly brace of the preceding catch block.Statements within this block are also indented. The finally block contains the code for cleaning up after a try or a catch. This block of code is always executed regardless of whether an exception is thrown or not in the try block. This remains true even if return, continue or break are executed. Four different scenarios are possible in a try-catch-finally block. First, a forced exit occurs when the program control is forced to skip out of the try block using a return, a continue or a break statement. Second, a normal completion happens when the the try-catch-finally statement executes normally without any error occurring. Third, the program code may have specified in a particular catch block the exception that was thrown. This is called the caught exception thrown scenario. Last, the opposite of the third scenario is the uncaught exception thrown. In this case, the exception thrown was not specified in any catch block. These scenarios are seen in the following code. class FinallyDemo { static void myMethodint n throws Exception{ try { switchn { case 1: System.out.printlnfirst case; return; case 3: System.out.printlnthird case; throw new RuntimeExceptionthird case demo; case 4: System.out.printlnfourth case; throw new Exceptionfourth case demo; case 2: System.out.printlnsecond case; } } catch RuntimeException e { System.out.printRuntimeException caught: ; System.out.printlne.getMessage; } finally { Introduction to Programming II Page 28 J.E.D.I. System.out.printlntry-block is entered.; } } public static void mainString args[]{ for int i=1; i=4; i++ { try { FinallyDemo.myMethodi; } catch Exception e{ System.out.printException caught: ; System.out.printlne.getMessage; } System.out.println; } } } The following lines are the expected output of this program. first case try-block is entered. second case try-block is entered. third case RuntimeException caught: third case demo try-block is entered. fourth case try-block is entered. Exception caught: fourth case demo Introduction to Programming II Page 29 J.E.D.I.

2.4 Throwing Exceptions