publicclassExceptionDemo2{publicstaticvoidmain(String[] argv){newExceptionDemo2().doTheWork();}publicvoiddoTheWork(){Object o =null;for(int i =0; i <5; i++){try{
o =makeObj(i);}catch(IllegalArgumentException e){System.err.println("Error: ("+ e.getMessage()+").");return;}finally{System.err.println("All done");if(o ==null)System.exit(0);}System.out.println(o);}}publicObjectmakeObj(int type)throwsIllegalArgumentException{if(type ==1)thrownewIllegalArgumentException("Don't like type "+ type);returnnewObject();}}
结果
上面的代码示例将产生以下结果。
All done
java.lang.Object@1b90b39Error:(Don't like type 1).All done
以下是java中finally块的另一个示例示例
publicclassHelloWorld{publicstaticvoidmain(String[]args){try{int data =25/5;System.out.println(data);}catch(NullPointerException e){System.out.println(e);}finally{System.out.println("finally block is always executed");}System.out.println("rest of the code...");}}
上面的代码示例将产生以下结果。
5finally block is always executed
rest of the code...