java中的異常拋出
語法:
public class ExceptionTest{ public void 方法名(參數(shù)列表) throws 異常列表{ //調(diào)用會(huì)拋出異常的方法或者拋出新的異常(throw new Exception();) }}
注:throws 異常列表位于方法體之前,可拋出多種類型的異常,每個(gè)類型之間用逗號(hào)隔開
例如:
public class ExceptionTest{ public void divide(int one,int two) throws Exception{ if(two==0){ throw new Exception("兩數(shù)相除,除數(shù)不能為0!"); } else{ System.out.PRintln("兩數(shù)相除,結(jié)果為:"+one/two); } }}如果某個(gè)方法調(diào)用到了會(huì)拋出異常的方法,有以下兩種解決方案:
1.添加try-catch去捕獲異常進(jìn)行處理
例如:
public class ExceptionTest { public static void main(String[] args) { try{ divide(5,0); // 調(diào)用了會(huì)拋出異常的方法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("兩數(shù)相除,除數(shù)不能為0!"); } else{ System.out.println("兩數(shù)相除,結(jié)果為:"+one/two); } }}運(yùn)行結(jié)果:兩數(shù)相除,除數(shù)不能為0!
2.添加throws聲明將異常拋出給更上一層的調(diào)用者(此方法無法處理異常,將異常再次拋出)
例如:
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("兩數(shù)相除,除數(shù)不能為0!"); } else{ System.out.println("兩數(shù)相除,結(jié)果為:"+one/two); } }}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注