標籤: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物件導向之異常(異常處理方式)