每次運行此代碼時,一切正常,但如果存款方法拋出錯誤,則只有catch主方法中的 捕獲例外并列印字串,盡管 catch在ExceptionsDemo. 為什么會這樣?
public class ExceptionsDemo {
public static void show() throws IOException {
var account = new Account();
try {
account.deposit(0);//this method might throw an IOException
account.withDraw(2);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
}
}
public class Main {
public static void main(String[] args) {
try {
ExceptionsDemo.show();
} catch (IOException e) {
System.out.println("An unexpected error occurred");
}
}
}
uj5u.com熱心網友回復:
發生這種情況是因為在您的show()方法中,您正在捕獲一種稱為InsufficientFundsException. 但例外的拋出account.deposit()就是IOException它被捕獲只在您的主要方法。這就是為什么執行 main 方法中的 catch 而不是 ExcpetionsDemo 中的 catch
如果你想在你的 ExceptionsDemo 類中捕獲 IOException 你可以這樣做:
public static void show() {
var account = new Account();
try {
account.deposit(0);//this method might throw an IOException
account.withDraw(2);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
單個 try 塊可以為每種型別的例外提供多個 catch 塊,并且可以通過在每個 catch 塊中對其進行編碼來根據您的需要自定義每個例外的處理。
uj5u.com熱心網友回復:
您的 ExceptionsDemo 拋出 a IOException,您的catchinExceptionsDemo 僅捕獲 aInsufficientFundsException因此它不會被捕獲在 中ExceptionsDemo,它將冒泡到呼叫者,并在那里被捕獲,前提是有一個catch塊來處理所述例外,它確實如此,否則您將有一個未捕獲的例外。它沒有被重新拋出ExceptionsDemo,因為它首先沒有被抓住
uj5u.com熱心網友回復:
try {
// do what you want
} catch (InsufficientFundsException e) {
// catch what you want
} catch (Exception e) {
// catch unexpected errors, if you want (optional)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/382750.html
