Site Search:

Create a try-catch block and determine how exceptions alter normal program flow


Back OCAJP




We have studied Exceptions, Errors, RuntimeExceptions and the guideline of how to handle them.

In this section, we will introduce finally block.

The finally block always came after catch block. When finally block is present, catch block is optional; when catch block is present, finally block is optional. The Curly braces are not optional.
The finally block always executes, whether or not an exception occurs in try and catch block.



OCAJP>cat test.java 
import java.util.*;
class test {
  public static void main(String...args) {
    test t = new test();
    t.tester();
  }
  public void tester() {
    try{}catch(Exception e){}
    try{}finally{}
    //try{} //error: 'try' without 'catch', 'finally' or resource declarations
    try{}catch(Exception e){}finally{System.out.println("execute without exception throw");}
    try{throw new Exception();}catch(Exception e){System.out.println("caught an Exception, swallow");}finally{System.out.println("execute no matter what");}
    try{
      throw new RuntimeException("throw from try");
    }catch(Exception e){
      System.out.println("The following exception is gonna to be swallowed in finally block");
      //throw new Exception(); //error: unreported exception Exception; must be caught or declared to be thrown
      throw new RuntimeException("throw from catch");
    }finally{
      System.out.println("All Error and RuntimeExceptions are caught here, its the chance to to something"); 
    }
  }
}
OCAJP>javac test.java 
OCAJP>java test
execute without exception throw
caught an Exception, swallow
execute no matter what
The following exception is gonna to be swallowed in finally block
All Error and RuntimeExceptions are caught here, its the chance to to something
Exception in thread "main" java.lang.RuntimeException: throw from catch
at test.tester(test.java:18)
at test.main(test.java:5)

Back OCAJP