OCA Java SE 8 Exception - Java try catch finally








Using a try Statement

Java uses a try statement to separate the code that might throw an exception from the code to handle that exception.

The code in the try block is run normally. If any of the statements throw an exception that can be caught by the exception type listed in the catch block, the try block stops running and execution jumps to the catch statement.

If none of the statements in the try block throw an exception that can be caught, the catch clause is not run.

The curly braces are required for the try and catch blocks.

3:void explore() { 
4:   try { 
5:       fall(); 
6:       System.out.println("never get here"); 
7:   } catch (RuntimeException e) { 
8:       getUp(); 
9:   } 
10:  walk(); 
11: } 
12: void fall() {  
13:     throw new RuntimeException(); 
14:} 

line 5 calls the fall() method. Line 13 throws an exception. Java jumps to the catch block, skipping line 6.

getup() on line 8 is called next and the try statement is over and execution proceeds normally with line 10.





finally Block

The try statement can have code within a finally clause regardless of whether an exception is thrown.

The syntax of a try statement with finally

A finally block can only appear as part of a try statement.

try { 
             //protected code 
} catch ( exceptiontype identifier ) { 
             //exception handler 
} finally { 
            //finally block 
}                                

If an exception is thrown, the finally block is run after the catch block. If no exception is thrown, the finally block is run after the try block completes.

12: void aDay() { 
13:   try { 
14:     walk(); 
15:     fall(); 
16:   } catch (Exception e) { 
17:     report(); 
18:   } finally { 
19:     keepWalking(); 
20:   } 
21:   goHome(); 
22: } 
23: void fall() {  
24:   throw new RuntimeException(); 
25: } 

The try catch and finally blocks must be in the right order.

25: try { // DOES NOT COMPILE 
26:   fall(); 
27: } finally { 
28:   System.out.println("all better"); 
29: } catch (Exception e) { 
30:   System.out.println("get up"); 
31: } 




Catch Various Types of Exceptions

class Exception1 extends RuntimeException { } 
class Exception2 extends RuntimeException { } 
class Exception3 extends Exception2 { } 

In the code above, there are three custom exceptions. All are unchecked exceptions because they directly or indirectly extend RuntimeException.

The following code catches both types of exceptions and handle them by printing out the appropriate message:

public void visitPorcupine() { 

  try { 
    seeShape(); 
  } catch (Exception1 e) {// first catch block 
    System.out.print("try back later"); 
  } catch (Exception2 e) {// second catch block 
    System.out.print("not today"); 
  } 
} 

If seeShape() doesn't throw an exception, nothing is printed out.

If the exception1 is thrown, only the first catch block runs.

If the exception2 is thrown, only the second catch block runs.

Java looks at exceptions in the order they appear in the catch statement.

If it is impossible for one of the catch blocks to be executed, a compiler error about unreachable code occurs. This happens when a superclass is caught before a subclass.

In the code above, the order of the catch blocks could be reversed because the exceptions don't inherit from each other.

The following example shows exception types that do inherit from each other:

public void aMethod() { 
  try { 
    seeShape(); 
  } catch (Exception3 e) {// subclass exception 
    System.out.print("try back later"); 
  } catch (Exception2 e) {// superclass exception 
    System.out.print("not today"); 
  } 
} 

If the more specific Exception3 exception is thrown, the first catch block runs. If not, Java checks if the superclass Exception2 exception is thrown and catches it.

The order of the catch blocks does matter in the code above.

The reverse does not work.

public void bMethod() { 
  try { 
    seeShape(); 
  } catch (Exception2 e) { 
    System.out.print("not today"); 
  } catch (Exception3 e) {// DOES NOT COMPILE 
    System.out.print("try back later"); 
  }  
} 

This time, if the more specific Exception3 exception is thrown, the catch block for Exception2 runs-which means there is no way for the second catch block to ever run.

Java compiler would tell us there is an unreachable catch block.

Do you see why this code doesn't compile?

public void cMethod() { 
  try { 
    seeShape(); 
  } catch (RuntimeException e) { 
    System.out.print("runtime exception"); 
  } catch (Exception2 e) {// DOES NOT COMPILE 
    System.out.print("not today"); 
  } catch (Exception e) { 
    System.out.print("exception"); 
  } 
} 

Exception2 is a RuntimeException. If it is thrown, the first catch block takes care of it, making sure there no way to get to the second catch block.

Throwing a Second Exception

The following code shows how to rethrow an exception from Java code.

try { 
  throw new RuntimeException(); 
} catch (RuntimeException e) { 
  throw new RuntimeException(); 
} finally { 
  throw new Exception(); 
}