#基本概念:
#例外處理的語法:
try {
// 可能會發生例外的程式碼
} catch (ExceptionType e) {
// 處理例外的程式碼
} finally {
// 無論是否發生例外,這裡的程式碼都會執行
}
#Java 實作範例:
// 自定義例外類別
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} catch (CustomException e) {
System.out.println("Custom Exception: " + e.getMessage());
} finally {
System.out.println("This will always be executed.");
}
}
public static int divide(int a, int b) throws CustomException {
if (b == 0) {
throw new CustomException("Divisor cannot be zero!");
}
return a / b;
}
}