Java(二)異常處理4.throw關鍵字
阿新 • • 發佈:2018-12-12
public class ThrowDemo { public static void main(String[] args) { try { int ret=divide(10,0); System.out.println(ret); }catch(ArithmeticException e) { System.out.println(e.getMessage()); } } private static int divide(int num1,int num2) { System.out.println("begin"); if(num2==0) { throw new ArithmeticException("除數不能為0"); } System.out.println("-------"); try { int ret=num1/num2; System.out.println("結果"+ ret); return ret; }catch(ArithmeticException e) { e.printStackTrace(); } System.out.println("end"); return 0; } }
throw和return類似,只是return返回一個值而throw返回一個錯誤 格式為throw new 錯誤型別(“異常資訊”)