目錄:
- 異常分類
- 聲明及拋出
- 捕獲異常
- 自定義異常
- 異常堆棧
異常指預期之外的各種狀況。
異常處理,即增強程序的魯棒性。
異常都是從throwable
類派生出來的,而throwable
類是直接從Object
繼承。
異常分類
- Error
系統內部錯誤,系統自行處理,無需捕捉。 - Exception
可以捕捉處理的異常。
也是平時需要主要關注的異常。
Exception 異常下主要有兩大類:- 派生於 RuntimeException 的異常
一般來說,RuntimeException都是程序員的問題。通常有以下幾種:
1.錯誤的數據類型轉換;
2.數組訪問越界;
3.算術異常;
4.訪問null指針。 - 非 RuntimeException 異常(受查異常)
一般有以下幾類:
1.打開了不存在的文檔;
2.未找到具體指定名稱的類;
3.操作文件異常。
- 派生於 RuntimeException 的異常
- RuntimeException
可以捕獲,也可以不捕獲的異常。 - 繼承 Exception 的其它類
必須捕獲,通常在API文檔中會說明這些方法會拋出哪些異常。
聲明及拋出
- 拋出異常
// ThrowTest.java
// 拋出異常 throw new 異常名();
public class ThrowTest{
public static void main(String[] args){
Integer a = 1;
Integer b = null;
if (a == null || b == null){
throw new NullPointerException();
} else {
System.out.println(a + b);
}
}
}
- 聲明異常
// ThrowsTest.java
// throws
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ThrowsTest{
public static void main(String[] args) throws FileNotFoundException{
throwsTest();
}
public static void throwsTest() throws FileNotFoundException{
new FileInputStream("/home/project/shiyanlou.file");
}
}
捕獲異常
在處理異常時,並不要求完全匹配異常,子類也可以匹配父類。處理多個異常時,需要注意。
// MultipleCaptureDemo.java
// try .. catch .. finally
// 將可能發生錯誤的語句放在try語句塊中,異常發生後要執行的語句放在catch語句塊中,finally語句塊中語句不論異常是否發生都會執行。
// 當程序中有多個異常時,可以通過catch來分別處理,但當前面的異常匹配後,後面的異常不再處理
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class MultipleCaptureDemo{
public static void main(String[] args){
try {
new FileInputStream("");
} catch (FileNotFoundException e){
System.out.println("IO 異常");
} catch (Exception e){
System.out.println("異常");
} finally {
System.out.println("結束");
}
}
}
自定義異常
繼承 Exception 或其子類即可。
建議同時提供無參和帶字符串參數的構造方法,便於在調試時提供更詳細的信息。
// MyAriException.java
public class MyAriException extends ArithmeticException{
public MyAriException(){
}
public MyAriException(String msg){
super(msg);
}
}
// ExceptionTest.java
import java.util.Arrays;
public class ExceptionTest{
public static void main(String[] args){
int[] array = new int[5];
Arrays.fill(array, 5);
for (int i = 4; i > -1; i--){
if (i == 0){
throw new MyAriException("Exception occured.");
} else {
System.out.println("array[" + i + "] / " + i + " = " + array[i] / i);
}
}
}
}
異常堆棧
異常拋出後,通過異常堆棧追蹤程序的運行軌跡,以便更好的debug。
// ExceptionStackTrace.java
public class ExceptionStackTrace{
private static void method(){
method2();
}
private static void method2(){
throw new NullPointerException();
}
public static void main(String[] args){
try {
method();
} catch (Exception e){
e.printStackTrace();
}
}
}
/* *********************
java.lang.NullPointerException
at ExceptionStackTrace.method2(ExceptionStackTrace.java:7)
at ExceptionStackTrace.method(ExceptionStackTrace.java:3)
at ExceptionStackTrace.main(ExceptionStackTrace.java:12)
首先打印的是距離拋出異常最近的語句,然後是調用該方法的方法,然後是被調用的方法;
即自下而上的看,便是程序運行軌跡。
*/