Java異常處理原理與用法實例分析
本文實例講述了Java異常處理原理與用法。分享給大家供大家參考,具體如下:
本文內容: 異常的介紹 處理異常 斷言首發日期:2018-03-26
異常: 異常是程序運行中發生的錯誤,比較常見的比如“除零異?!保绻粋€除數為零,那么會發生這個異常 異常會影響程序的正常運行,所以我們需要處理異常。
算術異常類:ArithmeticExecption
空指針異常類:NullPointerException
類型強制轉換異常:ClassCastException
數組下標越界異常:ArrayIndexOutOfBoundsException
輸入輸出異常:IOException
處理異常: 異常的捕獲:try…catch…finally 格式:
public class Demo { public static void main(String[] args) {// int a=10/0; try{ int a=10/0; }catch(ArithmeticException e) { System.out.println('run in ArithmeticException '+e); //run in ArithmeticException java.lang.ArithmeticException: / by zero } catch (Exception e) { System.out.println(e); }finally { System.out.println('最終執行的');//最終執行的 } }} 異常的聲明:
throws用于聲明異常,聲明函數可能發生的異常?!井敽瘮抵杏衪hrow來拋出異常時,函數頭必須使用throws聲明異?!?/p> 拋出異常:
throw用于手動拋出異常,可以拋出自定義異常信息:throw 異常類型(異常信息)
public class Demo2 { static int div(int a,int b) throws ArithmeticException{ if (b==0){ throw new ArithmeticException('發生除零異常了!'); } return a/b; } public static void main(String args[]) { try { System.out.println(div(2,0)); }catch(ArithmeticException e) { System.out.println(e.getMessage());//發生除零異常了! }finally { System.out.println('in finally');//in finally } System.out.println('after finally');//after finally }}
一般對于不想在函數中處理異常時,一般采用異常拋出處理(throw throws);否則使用try…catch…finally捕獲異常。
自定義異常:有時候沒有定義我們想要的異常(比如我們MYSQL連接異常),那么我們可以自定義異常。
所有異常都必須是 Throwable 的子類。 如果希望寫一個檢查性異常類(是一些編譯器會幫忙檢查的異常),則需要繼承 Exception 類。 如果你想寫一個運行時異常類(異常比如說,數組下標越界和訪問空指針異常),那么需要繼承 RuntimeException 類【這種異常類不需要throws】。class MyException extends Exception{ public MyException() {} public MyException(String msg) { super(msg); }}public class Demo3 { static int div(int a,int b) throws MyException { if (b==0){ throw new MyException('發生異常了!'); } return a/b; } public static void main(String args[]) { try { System.out.println(div(2,0)); }catch(Exception e) { System.out.println(e);//異常.MyException: 發生除零異常了! } }}斷言: assertion(斷言)在軟件開發中是一種常用的調試方式 斷言一般是判斷條件是否符合來決定程序是否繼續執行的。【比如,你要吃飯,那么assert一下飯到手了沒有,不然你可能會吃空氣】 斷言的開啟:eclipse、myeclipse的assert默認是關閉,想開啟assert需要在設置perferences-》Java-》installed jres中配置一下虛擬機參數,配置成-ea或者-enableassertions Java中使用assert來定義斷言:格式:assert [boolean 表達式]
public class Demo { public static void main(String[] args) { Boolean food=false; System.out.println('準備開始吃飯'); assert food;System.out.println('飯來了'); }}
更多java相關內容感興趣的讀者可查看本站專題:《Java面向對象程序設計入門與進階教程》、《Java數據結構與算法教程》、《Java操作DOM節點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章:
