Java物件導向之異常(異常處理方式)

來源:互聯網
上載者:User

標籤:demo   不能   遇到   exce   使用   java物件導向   rac   out   image   

一、基礎概念

  (1)異常:Java程式在運行時期發生的不正常情況。

     Java就按照物件導向的思想對不正常情況進行描述和對象的封裝。

  (2)異常問題分類: (Throwable:定義對於問題共性的功能。)

     1.Error:由系統底層發生的,jvn告訴使用者。不做針對性處理,直接修改代碼。

     2.Exception:發生並告訴使用者,可以進行針對性的處理。

  (3)異常的處理情況:

    1.遇到問題不進行具體的處理,繼續拋給調用者。就是在函數上通過throws關鍵字聲明異常。目的是讓調用者可以進行處理。

    2.針對性的處理方式:捕獲!
      try
      {
      //有可能發生異常的代碼。
      }
      catch(異常類 變數)
      {
      //這是真正的捕獲,處理異常的代碼;
      }
      finally
      {
      //一定會被執行的代碼。
      }

 

 二、異常處理代碼(一)

 1 class Demo 2 { 3     int div(int a,int b)throws Exception//聲明異常Exception 4     { 5         return a/b; 6     } 7 } 8      9 class ExceptionDemo110 {11     public static void main (String[] arge)throws Exception//將異常Exception拋給虛擬機器處理12     {13         Demo d = new Demo();14         int num = d.div(4,0);15         System.out.println("num="+num);16         System.out.println("over");17     }18 }

  

 三、異常處理代碼(二)


 
 1 class Demo 2 { 3     int div(int a,int b)throws Exception//聲明異常Exception 4     {     5         return a/b;//throw new ArithmeticException("/ by zero")拋給調用者。 6     } 7 } 8      9 class ExceptionDemo110 {11     public static void main (String[] arge)12     {13         Demo d = new Demo();14         15         //對異常進行處理16         try17         {18             int num = d.div(4,0);19             System.out.println("num="+num);20         }21         catch(Exception e)22         {23             //處理這個對象,可以使用該對象的方法。24             System.out.println("處理異常的代碼:除數不能為0");25             System.out.println(e.getMessage());//異常資訊26             System.out.println(e.toString());//異常名稱+異常資訊27             e.printStackTrace();//異常名字+異常資訊+位置。jvm預設處理收到異常就是調用這個方法。將資訊顯示在螢幕上。28         }29         System.out.println("over");30     }31 }

 

  

 

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.