Java異常處理
1:概念:
異常是java程序中運行時出現的錯誤的一種機制。
拋出異常是指程序中如果出現異常,則拋出實例, 通過實例封裝了異常的信息提交到Java運行時系統,這個過程叫做拋出異常。
Exception 這個術語是對詞組“ exceptional event ”簡短表達,其定義如下:
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program.
當在一個方法內部發生了一個錯誤,這個方法就創建一個對象并把它發送給運行系統,然后離開它。這個對象就是 exception object ,包含了有關錯誤的相關信息(錯誤發生時的程序狀態及錯誤的類型)。創建一個 exception 對象并向運行系統發送,被稱為“ throwing an exception ”。
當一個方法拋出異常后,運行系統便試著查找原因并處理它。 The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).
2.異常體系結構
3:Java異常的關鍵字
try :標示程序將要發生的異常語句塊
catch:捕獲異常,先拋小異常,在拋出大異常。
finally 不管try語句塊中是否拋出異常都要執行finally塊的語句,此關鍵字的好處是:如果打開數據庫鏈接程序中斷,可以在此處關閉鏈接,例如:打開文件,IO流文件
throw 在方法中拋出異常指向一個異常方法
throws 拋出方法異常。
注意:聲明方法異常時則需要在重寫方法時,重寫的方法和原方法保持一致或者不拋出方法異常。
4:語法結構
try { //程序語句塊 System.out.println("開始執行異常..."); System.out.println("程序運行結果:"+10/0); System.out.println("結束執行異常..."); } catch(ArithmeticException e) { e.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); }
Connection conn =null; try { conn = DriverManager.getConnection("","",""); //程序語句塊 System.out.println("開始執行異常..."); System.out.println("程序運行結果:"+10/0); System.out.println("結束執行異常..."); } catch(ArithmeticException e) { e.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } finally { try { if(conn!=null) { conn.close(); conn=null; } } catch(Exception io) { io.printStackTrace(); } }
例子:
package com.ith.study; import java.sql.Connection; import java.sql.DriverManager; @SuppressWarnings("serial") public class DefaultException extends Exception { public DefaultException() { super(); //調用父類構造方法 } public DefaultException(final String msg) { //super(msg); System.out.println(msg+"============"); } }
package com.ith.study; import com.ith.study.DefaultException; public class ThrowsException { /** * @param args * @throws DefaultException */ public static void main(String[] args) { // TODO Auto-generated method stub ThrowsException throwtest=new ThrowsException(); throwtest.throwsTestException(); } public void throwsTestException() { System.out.println("==================="); int i= 7/2; System.out.println("7/2======"+i); if(i>0) { try { throw new DefaultException("7/2拋出自定義異常"); } catch (DefaultException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
