26 異常
定義
程序中運行時出現的錯誤
分類
從是否主動產生可分爲:
1.java中已經預定義好的異常(ArrayIndexoutofException和nullPointerException)
2.自行定義的異常(如AgeException)
從開發者角度可分爲:
1.Exception異常(程序中出現的錯誤)
2.Error異常(JVM錯誤,程序無法處理)
補充:Throwable類是Exception和Error的父類
處理異常的機制
1.捕捉異常(try.......catch)-------主動
try{
//可能發生異常的語句
}catch(異常類 異常對象){
//異常處理語句
}catch(異常類 異常對象){
//異常處理語句
}finally{
//調用try catch時一定會執行的代碼,不管你在try所在的普通代碼塊中有沒有產生異常
}
//異常處理語句可以有很多即catch{}可以續寫很多次
public class ExceptionDemo1{
public static void main(String args[]){
int i=10;
int j=0;
try{
int trmp=i/j;
System.out.println("程序沒有出現異常");
}catch(ArithmeticException e){
System.out.println("出現異常了: "+e);
}finally{
System.out.println("try---catch--finally操作處理完畢!!!");
}
}
}
2.交給方法調用處處理
throws
public 返回值類型 方法名稱(參數1,參數2......參數n) throws Exception{
}
public class A{
public void print() throws Exception{
int i=10;
int j=0;
int trmp=i/j;
System.out.println("程序沒有出現異常");
}
}
//類A中print()方法出現的異常(運行錯誤)會丟給調用 類A print()方法處處理
public class ExceptionDemo1{
public static void main(String args[]){
A a=new A();
a.print();//異常在這裏一定得處理,不然會報錯
}
}
注意:理論上任何方法都可以拋異常,但不建議在main函數中拋異常,因爲這個時候它會把異常交給jvm處理,得不到任何有效的異常信息了.
3.拋出異常
throw new Exception("自己拋的異常");
//拋出異常時直接拋出異常的實例化對象即可
//這個新拋出的異常也需要處理
4.面試題補充
RuntimeException和Exception的區別,請列舉幾個常見的RunTimeException
(1)RuntimeException是Exception的子類
(2)Exception定義了必須處理的異常,而RunTimeException定義的異常可以選擇型處理
(3)常見的RunTimeException:
a. NumberFormatException、
b. ClassCastException、
c. NullPointerException
d. ArithmeticException、
e. ArrayIndexOutOfBoundsException