線程終止
異常拋出主要有error和exception兩種,error程序直接終止,線程當然就是終止了;exception分爲兩種運行時和編譯時,運行時異常常被捕獲或拋出,程序會繼續運行,沒有被捕獲線程就停止了;而編譯時異常直接就無法完成編譯了。
編譯時異常 | 運行時異常 |
---|---|
SQLException | NullPointerException |
IOException | ClassCastException(對象強制類型轉換出錯) |
ClassNotFoundException | ArrayIndexOutOfBoundsException(數組下標越界) |
ArithmeticException(算數錯誤情形) |
異常處理
1、標準錯誤輸出流
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.println("請輸入被除數:");
try {
int num1=input.nextInt();
System.out.println("請輸入除數:");
int num2=input.nextInt();
System.out.println(String.format("%d / %d = %d",
num1, num2, num1 / num2));
}catch (Exception e) {
System.err.println("出現錯誤:被除數和除數必須是整數,"+
"除數不能爲零。");
System.out.println(e.getMessage());
}
}
System.err.println():標準錯誤輸出流,這種輸出方式可以輸出錯誤的消息,在控制檯呈現紅色。
2、try-catch、try-catch-finally、多重catch塊
try-catch-finally 程序塊的流程大致分爲兩種情況:
- 如果try塊中所有語句正常執行完畢,那麼finally塊就會被執行。
- 如果try語句在執行過程中碰到異常,無論這種異常能否被catch塊捕獲到,都將執行finally塊中的代碼。
- 在寫異常處理的時候,一定要把異常範圍小的放在前面,範圍大的放在後面
try-catch-finally結構中try塊是必須有的,catch和finally塊爲可選,但兩者至少必須出現其中之一
3、try-catch-finally中包含return的情況
public class Main {
public static void main(String args[]) {
// 順序執行即可
try {
} catch () {
} finally {
}
return;
// 執行try塊中(異常時執行catch())的return之前的代碼,然後執行finally塊,
// 最後執行try塊(或者catch)中的return。
// 此時程序已經返回,不再執行finally{}後面的return了。
try {
return;
} catch () {
return;
} finally {
}
return;
// 執行try或者catch中的return語句之前,都會先執行finally語句,
// 如果finally中有return語句,那麼程序就直接return了。
try {
return;
} catch () {
return;
} finally {
return;
}
return;
}
}
總結:如果finally存在的話,任何執行try 或者catch中的return語句之前,都會先執行finally語句, 如果finally中有return語句,那麼程序就return了。所以finally中的return是一定會被return的,編譯器把finally中的return實現爲一個warning。
4、throws 和 throw
throws 聲明異常,throws是用來聲明一個方法可能拋出的所有異常信息,throws是將異常聲明但是不處理,而是將異常往上傳,誰調用我就交給誰處理。
throw 拋出異常,throw拋出的一個具體的異常類型。
public class Test {
// throws 聲明異常
public static void Test3() throws NumberFormatException{
String s = "abc";
System.out.println(Double.parseDouble(s));
}
public static void main(String[] args) {
try {
Test3();
} catch (NumberFormatException e) {
// 捕獲異常
System.err.println("非數據類型不能轉換。");
}
}
}
public class Test2 {
public static void main(String[] args) {
String s = "abc";
if(s.equals("abc")) {
// throw 拋出異常,throw(異常對象)
throw new NumberFormatException();
} else {
System.out.println(s);
}
}
}