動手動腦(五 異常處理)
阿新 • • 發佈:2018-11-10
1 package class5; 2 3 import javax.swing.JOptionPane; 4 5 class AboutException { 6 public static void main(String[] a) 7 { 8 int i=1, j=0, k; 9 k=i/j; 10 11 12 try 13 { 14 15 k = i/j; // Causes division-by-zero exception16 //throw new Exception("Hello.Exception!"); 17 } 18 19 catch ( ArithmeticException e) 20 { 21 System.out.println("被0除. "+ e.getMessage()); 22 } 23 24 catch (Exception e) 25 { 26 if (e instanceof ArithmeticException)27 System.out.println("被0除"); 28 else 29 { 30 System.out.println(e.getMessage()); 31 32 } 33 } 34 35 36 finally 37 { 38 JOptionPane.showConfirmDialog(null,"OK"); 39} 40 41 } 42 }
1.AboutException:
一般情況下在沒有定義提供相應的異常處理程式碼,JVM將會結束掉整個應用程式。當自己定義異常異常處理方法時,把可能出現錯誤的程式碼放在try語句中,當執行該程式碼時會時時的進行監控,只要程式碼
中出現錯誤,就會丟擲一個異常物件,異常處理程式碼就會捕獲並且處理這個錯誤,錯誤的處理程式碼將放在catch語句中,當異常發生時,程式控制流程由try語句塊跳轉到catch語句塊,不管是否有異常
發生,finally語句塊中的語句始終保證被執行。
2.CatchWho.java:
執行結果:
3.CatchWho2.java:
執行結果:
4.EmbedFinally.java:
1 package class5; 2 3 4 public class EmbededFinally { 5 6 7 public static void main(String args[]) { 8 9 int result; 10 11 try { 12 13 System.out.println("in Level 1"); 14 15 16 try { 17 18 System.out.println("in Level 2"); 19 // result=100/0; //Level 2 20 21 try { 22 23 System.out.println("in Level 3"); 24 25 result=100/0; //Level 3 26 27 } 28 29 catch (Exception e) { 30 31 System.out.println("Level 3:" + e.getClass().toString()); 32 33 } 34 35 36 finally { 37 38 System.out.println("In Level 3 finally"); 39 40 } 41 42 43 // result=100/0; //Level 2 44 45 46 } 47 48 catch (Exception e) { 49 50 System.out.println("Level 2:" + e.getClass().toString()); 51 52 } 53 finally { 54 55 System.out.println("In Level 2 finally"); 56 57 } 58 59 // result = 100 / 0; //level 1 60 61 } 62 63 catch (Exception e) { 64 65 System.out.println("Level 1:" + e.getClass().toString()); 66 67 } 68 69 finally { 70 71 System.out.println("In Level 1 finally"); 72 73 } 74 75 } 76 77 }
執行結果
總結:當有多層巢狀的finally時,異常在不同的層次丟擲 ,在不同的位置丟擲,可能會導致不同的finally語句塊執行順序
5.finally語句塊一定會執行嗎?
SystemExitAndFinally.java
1 package class5; 2 3 4 public class SystemExitAndFinally { 5 6 7 public static void main(String[] args) 8 { 9 10 try{ 11 12 13 System.out.println("in main"); 14 15 throw new Exception("Exception is thrown in main"); 16 17 //System.exit(0); 18 19 20 } 21 22 catch(Exception e) 23 24 { 25 26 System.out.println(e.getMessage()); 27 28 System.exit(0); 29 30 } 31 32 finally 33 34 { 35 36 System.out.println("in finally"); 37 38 } 39 40 } 41 42 43 }
執行結果:
由結果可知,在此程式中並沒有執行finally語句,因為程式中使用了system.exit語句,使得程式在執行finally語句之前就終止了。
6.
之所以會出現這種不同的情況,是因為在處理int除以0時javac生成了idiv位元組碼指令,而double型別生成了ddiv位元組碼指令。
JVM在具體實現這兩個指 令時,採用了不同的處理 策略,導致兩段程式碼執行 時得到不同的結果。