Java 異常 - Try...Catch
Java 異常
在執行 Java 程式碼時,可能會發生各種錯誤:程式設計師編寫的編碼錯誤、由於輸入錯誤導致的錯誤,或者其他無法預見的情況。
當發生錯誤時,Java 通常會停止執行並生成錯誤訊息。這在技術上稱為:Java 將**丟擲異常**(丟擲一個錯誤)。
Java try 和 catch
try
語句允許您定義一個程式碼塊,在執行時對其進行錯誤測試。
catch
語句允許您定義一個程式碼塊,在 `try` 塊中發生錯誤時執行。
try
和 catch
關鍵字成對出現
語法
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
請看下面的例子
這將生成一個錯誤,因為 myNumbers[10] 不存在。
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
輸出可能類似於:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)
注意: 當您嘗試訪問不存在的索引號時,會發生 ArrayIndexOutOfBoundsException
。
如果發生錯誤,我們可以使用 try...catch
來捕獲錯誤並執行一些程式碼來處理它
示例
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
輸出將是:
發生了錯誤。
Finally
finally
語句允許您在 try...catch
之後執行程式碼,無論結果如何。
示例
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
輸出將是:
發生了錯誤。
The 'try catch' is finished.
throw 關鍵字
throw
語句允許您建立自定義錯誤。
throw
語句與**異常型別**一起使用。Java 中有許多可用的異常型別:ArithmeticException
、FileNotFoundException
、ArrayIndexOutOfBoundsException
、SecurityException
等等。
示例
如果 age 小於 18,則丟擲異常(列印 "Access denied")。如果 age 為 18 或更大,則列印 "Access granted"
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
輸出將是:
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
如果 age 是 20,您將**不會**收到異常
錯誤和異常型別參考
有關不同錯誤和異常型別的列表,請訪問我們的 Java 錯誤和異常型別參考。