使用 try ... catch 捕捉例外
try {
檢查是否例外的程式區塊
} catch (例外類別 變數名稱) {
例外發生時,執行的區塊
}
範例
public class ExceptionZero {
public static void main(String[] args) {
try {
int a = 5;
int b = 0;
System.out.println("Answer: " + a/b);
} catch (ArithmeticException e) {
System.out.println("例外錯誤:除數為 0:"+ e.toString());
}
}
}
執行結果
使用 try ... catch ... finally 捕捉例外
try {
檢查是否例外的程式區塊
} catch (例外類別 變數名稱) {
例外發生時,執行的區塊
} finally {
絕對會執行的程式區塊
}

沒有留言:
張貼留言