Java:異常處理,java異常處理

來源:互聯網
上載者:User

Java:異常處理,java異常處理
本文內容:

  • 異常的介紹
  • 處理異常
  • 斷言

 

 

 首發日期:2018-03-26

異常:
  • 異常是程式運行中發生的錯誤,比較常見的比如“除零異常”,如果一個除數為零,那麼會發生這個異常
  • 異常會影響程式的正常運行,所以我們需要處理異常。
  • 所有的異常類是從 java.lang.Exception 類繼承的子類。 異常類有兩個主要的子類:IOException 類和 RuntimeException 類。

 

常見異常:

算術異常類:ArithmeticExecption

null 指標異常類:NullPointerException

類型強制轉換異常:ClassCastException

數組下標越界異常:ArrayIndexOutOfBoundsException

輸入輸出異常:IOException

 

處理異常:

 

  • 異常的捕獲:try…catch…finally
    • 格式:
    • try代碼塊:裡面放的是異常可能發生的代碼
    • catch代碼塊【可以有多個】:進行捕獲異常的操作
      • e是捕獲的異常類對象,直接列印會得到字串結果(包含異常的線程、類型、位置)
      • e.getMessage():只返回異常的類型+原因
      • e.printStackTrace(): 異常的類型+原因+位置
      • e.toString():異常的類型+原因
    • finally【可選】:放的是無論發生異常與否都會執行的代碼
    • 異常類如果無法確定類型而準確捕獲時,可以捕獲成所有異常類的父類Exception
    • 當異常捕獲成功後,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用於聲明異常,聲明函數可能發生的異常。【當函數中有throw來拋出異常時,函數頭必須使用throws聲明異常】

 

  • 拋出異常:

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 類。
  • 如果你想寫一個運行時異常類(異常比如說,數組下標越界和訪問null 指標異常),那麼需要繼承 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("飯來了");            }}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.