import javax.swing.*; class AboutException { public static void main(String[] a) { double i=-1, j=0, k; k=i/j; try { k = i/j; // Causes division-by-zero exception //throw new Exception("Hello.Exception!"); } catch ( ArithmeticException e) { System.out.println("被0除. "+ e.getMessage()); } catch (Exception e) { if (e instanceof ArithmeticException) System.out.println("被0除"); else { System.out.println(e.getMessage()); } } finally { JOptionPane.showConfirmDialog(null,"OK "+k); //JOptionPane.showInternalConfirmDialog(null, k); } } }
运行:
分析:
Try{
//可能发生运行错误的代码;
}
catch(异常类型 异常对象引用){
//用于处理异常的代码
}
finally{
//用于“善后” 的代码
}
Java 中所有可捕获的异常都派生自 Exception 类。
2. 阅读以下代码(CatchWho.java),写出程序运行结果:
运行结果:
3. 写出CatchWho2.java程序运行的结果
运行结果:
4.请先阅读 EmbedFinally.java示例,再运行它,观察其输出并进行总结。
public class EmbededFinally { public static void main(String args[]) { int result; try { System.out.println("in Level 1"); try { System.out.println("in Level 2"); // result=100/0; //Level 2 try { System.out.println("in Level 3"); result=100/0; //Level 3 } catch (Exception e) { System.out.println("Level 3:" + e.getClass().toString()); } finally { System.out.println("In Level 3 finally"); } // result=100/0; //Level 2 } catch (Exception e) { System.out.println("Level 2:" + e.getClass().toString()); } finally { System.out.println("In Level 2 finally"); } // result = 100 / 0; //level 1 } catch (Exception e) { System.out.println("Level 1:" + e.getClass().toString()); } finally { System.out.println("In Level 1 finally"); } } }
结果分析:
1)当有多层嵌套的finally时,异常在不同的层次抛出 ,在不同的位置抛出,可能会导致不同的finally语句块执行顺序。
2)try抛出一个异常之后,程序会跳出try,不再执行try后边的语句,开始对catch进行匹配,处理异常;
3)try嵌套中,抛出的异常只有被处理才可以按顺序抛出下一个异常,如果不处理,程序就终止;
4)try抛出异常之后,就跳出了try语句,内层catch无法捕获就继续向外抛,所以外层也就有异常,外层语句不执行,第二个程序 throw new ArithmeticExcepption没有执行。
5)第三个程序,try第一层第二层没有异常不用捕获,执行完之后到第三层,除0有异常,catch捕获,执行第三层的finally然后,顺序执行第二层,第一层的finally。
5. 辨析:finally语句块一定会执行吗?
请通过 SystemExitAndFinally.java示例程序回答上述问题
public class SystemExitAndFinally { public static void main(String[] args) { try{ System.out.println("in main"); throw new Exception("Exception is thrown in main"); //System.exit(0); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(0); } finally { System.out.println("in finally"); } } }
结论:
1)try语句嵌套从外层到内层执行,在try语句中,哪一层出错,哪一层就抛出异常,后边的try语句就不再执行,如果该层存在catch就进行相应的捕获,有该层的finally也执行,除非finally遇到不执行的情况;
2.try-catch-finally语句嵌套时,内层try抛出异常,即使catch没有捕捉到抛出的异常,内层的finally也一样会执行,然后异常继续向外抛出,除非遇到极特殊的System.exit(0)在finally语句之前的try-catch中,finally语句才不执行。