C語言時用if...else...來控制異常,Java語言所有的異常都可以用一個類來表示,不同類型的異常對應不同的子類異常,每個異常都對應一個異常類的對象。
Java異常處理通過5個關鍵字try、catch、finally、throw、throws進行管理。基本過程是用try包住要監視的語句,如果在try內出現異常,則異常會被拋出,catch中捕獲拋出的異常並做處理,finally一定會完成未盡事宜。
練習:
package com.swift; public class Exception1 { public static void main(String args[]){ System.out.println("=========計算開始========="); try{ int i=Integer.parseInt(args[0]); int j=Integer.parseInt(args[1]); int temp=i/j; System.out.println("計算結果:"+ temp); }catch(ArithmeticException e){ System.out.println("出現了數學異常 "+ e); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("出現了數組異常 "+ e); }catch(NumberFormatException e){ System.out.println("出現了格式異常 "+ e); }catch(Exception e){ System.out.println("其他異常 "+e); }finally{ System.out.println("不管是否有異常,我都執行。"); } System.out.println("=========計算結束========="); } }
throws標識此方法出異常但不處理,誰調誰處理。
package com.swift; public class Exception3 { public static void main(String args[]) throws Exception{ Operate o=new Operate(); System.out.println("=============計算之前=============="); int temp=o.div(Integer.parseInt(args[0]),Integer.parseInt(args[1])); System.out.println("計算結果"+temp); System.out.println("=============計算之后=========="); } } class Operate { public int div(int i,int j) throws Exception{ int temp=i/j; return temp; } }
如果main也throws了,異常拋給了JVM,其實你一個throws不寫,JVM依然會默默地處理着異常
注意:一旦方法throws,main必須有回應,否則編譯不過。main繼續拋相當於出異常之后的程序戛然而止(沒有"=============計算之后=========="),這時可用catch捕獲拋來的異常進行處理。
package com.swift; public class Exception3 { public static void main(String args[]) throws Exception{ Operate o=new Operate(); System.out.println("=============計算之前=============="); try { int temp=o.div(Integer.parseInt(args[0]),Integer.parseInt(args[1])); System.out.println("計算結果"+temp); }catch(Exception e){ System.out.println("出現了什么異常情況 "+e); } System.out.println("=============計算之后=========="); } } class Operate { public int div(int i,int j) throws Exception{ int temp=i/j; return temp; } }
異常被處理,計算前后正常輸出。
throw與throws不同,throw拋出的不是異常類,而是對象,可以人造的對象。
package com.swift; public class Exception4 { public static void main(String args[]) { try { throw new Exception("拋着玩呢 "); // 拋出人造異常對象 } catch (Exception e) { // 再捕捉這個對象 System.out.println("你拋的是什么呢?"+e); } } }
如果不想拋Exception類的對像,要拋自己的
package com.swift; public class Exception5 { public static void main(String args[]) { try { throw new MyException("自定義異常。"); } catch (Exception e) { System.out.println("這個異常是 " + e); // e.printStackTrace(); } } } //通過繼承實現自己的異常類 class MyException extends Exception { public MyException(String msg) { //把參數傳給父類 super(msg); } }