最清楚的java異常機制
技術標籤:java
異常
異常是指程式在執行時出現錯誤時通知給呼叫者的一種機制
java異常體系
- 頂層Throwable派生兩個子類,error和Exception;
- Error是指java執行時內部錯誤和資源耗盡錯誤,應用程式不丟擲此類異常,這種內壁錯誤一旦出現,告知使用者程式終止,不做任何處理
- Exception指的是異常的父類。
- RuntimeException類的所有異常稱為非受查異常,所有其他異常稱為受查異常
常見的異常
除0
System.out.println(10/0)
Exception in thread “main” java.lang.ArithmeticException: / by zero
陣列下標越界
int [] a = {1,2,3,4,5};
System.out.println(a[10]); Exceptioninthread"main"java.lang.ArrayIndexOutOfBoundsException: 10
空指標
class A { public int n =10; } A a = null; System.out.println(a.n);;
Exception in thread “main” java.lang.NullPointerException
異常的用法
try{
可能出現異常的語句
}catch(異常型別 異常物件) {
...
}finally{
異常的出口
}
try程式碼塊中放的是可能出現異常的程式碼
catch程式碼塊放的是可能出現異常後的行為
finally 程式碼塊中的程式碼會在最後執行
catch、finally可以視情況新增
若catch中有多個異常,若即有子類異常也有父類異常時,必須將父類異常寫在子類異常後面
try{
}catch(NullPointerExceprion e)
{
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
異常的處理流程
舉個例子
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
try {
System.out.println(10 / a);
} catch (ArithmeticException e) {
e.printStackTrace();
}finally{
System.out.println("finally");
}
}
注意
public static void main(String[] args) {
int a =fun();
System.out.println(a);
}
static int fun(){
try{
return 3;
}catch (Exception e){
e.printStackTrace();
}finally {
return 5;
}
}
大多數人會覺得這個fun函式返回的結果是3,但是finally中的程式碼塊會必須被執行所以返回結果5,一般不建議在finally中新增return語句
- 程式先執行try中的程式碼
- 若try中程式碼出現異常,就會結束try中的程式碼,和catch中的異常型別進行匹配
- 如果找到匹配的異常型別,就會執行catch中的程式碼;反之,將異常向上傳遞到上層呼叫者
- 無論是否有找到匹配的異常型別,finally中的程式碼都會被執行
- 若上層呼叫者也沒有處理,就繼續向上層繼續傳遞
- 若到主方法也沒有處理,則會交給jvm來處理,此時程式會異常終止
受查異常的處理方式
//方式一 try/catch包圍
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
try {
String s = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
//方式二丟擲異常
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String s = reader.readLine();
}
當出現受查異常時必須顯示進行處理
1:使用try catch 包裹起來
2:在方法上加上異常說明,將處理動作交給上級呼叫者。
自定義異常
使用者自己實現的異常稱為自定義異常,通過繼承RuntimeException來實現自定義異常。使用者根據自己的業務邏輯進行自定義異常的書寫
class MyException extends RuntimeException{
public Exection(String message) {
super(message);
}
}
呼叫此異常通過 throw new MyException(“提示使用者的異常資訊”)
舉個例子
public class Exection extends RuntimeException{
public Exection(String message) {
super(message);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
if(a<0){
throw new Exection("請輸入一個正數");
}
}
}