java中的異常拋出
語法:
public class ExceptionTest{ public void 方法名(參數列表) throws 異常列表{ //調用會拋出異常的方法或者拋出新的異常(throw new Exception();) }}
注:throws 異常列表位于方法體之前,可拋出多種類型的異常,每個類型之間用逗號隔開
例如:
public class ExceptionTest{ public void divide(int one,int two) throws Exception{ if(two==0){ throw new Exception("兩數相除,除數不能為0!"); } else{ System.out.PRintln("兩數相除,結果為:"+one/two); } }}如果某個方法調用到了會拋出異常的方法,有以下兩種解決方案:
1.添加try-catch去捕獲異常進行處理
例如:
public class ExceptionTest { public static void main(String[] args) { try{ divide(5,0); // 調用了會拋出異常的方法divide(); }catch(Exception e){ System.out.println(e.getMessage()); } } public static void divide(int one,int two) throws Exception{ if(two==0){ throw new Exception("兩數相除,除數不能為0!"); } else{ System.out.println("兩數相除,結果為:"+one/two); } }}運行結果:兩數相除,除數不能為0!
2.添加throws聲明將異常拋出給更上一層的調用者(此方法無法處理異常,將異常再次拋出)
例如:
public class ExceptionTest { public static void main(String[] args) throws Exception { //添加throws聲明 divide(5,0); } public static void divide(int one,int two) throws Exception{ if(two==0){ throw new Exception("兩數相除,除數不能為0!"); } else{ System.out.println("兩數相除,結果為:"+one/two); } }}
新聞熱點
疑難解答