10.7抛出异常处理
生活随笔
收集整理的這篇文章主要介紹了
10.7抛出异常处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
異常的處理方式:------拋出異常處理
拋出異常處理(throw throws)
注意事項:1.如果一個方法的內部拋出一個異常 對象,那么必須要在方法上聲明拋出2.如果調用了一個聲明拋出異常的方法 ,那么調用者必須要處理異常。3.如果一個方法內部拋出了一個異常對象,那么throw語句后面的代碼都不會在執行。throw和throws 兩個關鍵字的區別:1.throw關鍵字是用于方法內部的,throws是用于方法聲明上的。2.throw關鍵字是用于方法內部拋出一個異常對象的,throws關鍵字是用于在方法聲明上拋出異常類型。3.throw關鍵字后面只能有一個異常對象,throws后面一次可以聲明拋出多種類型的異常。
class ThrowException {public static void main(String[] args) throws Exception //拋給JVM{try{div(3,0);}catch (Exception e){System.out.println(" 出現異常 ");e.printStackTrace();}}public static void div(int a,int b)throws Exception {if(b == 0){throw new Exception();}int c = a/b;System.out.println(" c= "+c);} }
class ThrowException {public static void main(String[] args) throws Exception //拋給JVM{try{div(3,0);}catch (Exception e){System.out.println(" 出現異常 ");e.printStackTrace();}}public static void div(int a,int b)throws Exception {if(b == 0){throw new Exception();}int c = a/b;System.out.println(" c= "+c);} }
總結
以上是生活随笔為你收集整理的10.7抛出异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 10.6 捕获处理异常
- 下一篇: 11.1自定义异常类