Java 異常基礎知識總結

來源:互聯網
上載者:User

標籤:運行時異常   nal   繼承   虛擬   mat   div   bsp   catch   static   


RuntimeException類是Exception類的子類,它叫做運行時異常,Java中的所有運行時異常都會直接或者間接地繼承自RuntimeException類。

RuntimeException

Java中凡是繼承自Exception,而不繼承自RuntimeException類的異常都是非運行時異常。

Exception在程式中必須使用try……catch進行處理;而RuntimeException可以不使用try……catch進行處理,但是如果有異常產生,
則異常交給JVM(java虛擬機器(java virtual machine))處理,程式無法處理。

Throwable 類是 Java 語言中所有錯誤或異常的超類(這就是一切皆可拋的東西)。它有兩個子類:Error和Exception。

對於非運行時異常(checked exception),必須要對其進行處理,否則無法通過編譯。
處理方式有兩種:
  1.使用try..catch..finally進行捕獲;
  2.在產生異常的方法聲明後面寫上throws 某一個Exception類型,如throws Exception,將異常拋出到外面一層去。

在定義一個方法時可以使用throws關鍵字聲明,表示此方法不處理異常,而是交給方法調用處進行處理。

throw直接拋出異常類的執行個體化對象。往往拋出程式中已經產生的異常類執行個體。

1)
class Math{
  public int div(int i,int j) throws Exception{    //此方法可以不處理異常,即說明此方法中即使
                             不使用try……catch語句,所產生的異常也會由
                            調用處處理,例如下一個例子。
    System.out.println("…………計算開始…………");
    int temp = 0;
    try{
        temp = i/j;
    }catch (Exception e){
                throw e;//把異常交給調用處
    }finally{
            System.out.println("…………計算技術…………");
    }
      return temp;
  }
}

public class ThrowDemo02 {

  public static void main(String[] args) {
    Math m = new Math();
    try {
        System.out.println("除法操作:"+m.div(10,0));
    }catch(Exception e){
        System.out.println("異常產生:"+e);
    }

  }

}

2)
class Math{
  public int div(int i,int j) throws Exception{
      System.out.println("…………計算開始…………");
      int temp = 0;

      temp = i/j;

      return temp;
  }
}

public class ThrowDemo02 {

    public static void main(String[] args) {
      Math m = new Math();
      try {
          System.out.println("除法操作:"+m.div(10,0));
      }catch(Exception e){
          System.out.println("異常產生:"+e);
      }

    }
}

Java 異常基礎知識總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.