Web hosting solutions - 826 Exception Handling Chapter 14 If an exception
Tuesday, August 21st, 2007826 Exception Handling Chapter 14 If an exception occurs, the program skips the rest of the try block. If the program catches the exception in one of the catchhandlers, the program processes the exception. Then the finallyblock releases the resource, and control then proceeds to the first statement after the finallyblock. If an exception that occurs in the try block cannot be caught by one of the catch handlers, the program skips the rest of the tryblock and control proceeds to the finally block, which releases the resource. Then the program passes the exception up the call chain until some calling method chooses to catchit. If no method chooses to deal with it, a non- GUI-based application terminates. If a catchhandler throws an exception, the finallyblock still executes. Then the exception is passed up the call chain for a calling method to catchand handle. The Java application of Fig. 14.9 demonstrates that the finally block (if one is present) executes even if an exception is not thrown in the corresponding tryblock. The program contains methods main (lines 7 21), throwException (lines 24 50) and doesNotThrowException (lines 53 75). Methods throwException and does- NotThrowException are declared static so main (another static method) can call them directly. Method main begins executing, enters its try block and immediately calls throwException(line 11). Method throwExceptionthrows an Exception(line 29), catches it (line 33) and rethrows it (line 37). The rethrown exception will be handled in main, but first the finally block (lines 44 47) executes. Method main detects the rethrown exception in the try block in main(lines 10 12) and handles it by the catch block (lines 15 18). Next, main calls method doesNotThrowException (line 20). No exception is thrown in doesNotThrowException s try block, so the program skips the catch block (lines 61 64), but the finally block (lines 68 61) nevertheless executes. Control proceeds to the statement after the finallyblock. Then control returns to mainand the program terminates. 1 // Fig. 14.9: UsingExceptions.java 2 // Demonstration of the try-catch-finally 3 // exception handling mechanism. 4 public class UsingExceptions { 5 6 // execute application 7 public static void main( String args[] ) 8 { 9 // call method throwException 10 try { 11 throwException(); 12 } 13 14 // catch Exceptions thrown by method throwException 15 catch ( Exception exception ) 16 { 17 System.err.println( “Exception handled in main” ); 18 } 19 Fig. 14.9 Demonstration of the try-catch-finallyexception-handling mechanism (part 1 of 3).
If you are in need for cheap and reliable webhost to host your website, we recommend http web server services.