Everytime I run this code, everything works fine, but if deposit methods throws an error,
only the catch in the main method catches the exception and prints the string, despite the catch in the ExceptionsDemo. Why does that happen?
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");
}
}
}
Your ExceptionsDemo throws a
IOException, yourcatchinExceptionsDemoonly catches aInsufficientFundsExceptionso it will not be caught in theExceptionsDemo, it will bubble to the caller, and be caught there, providing there is acatchblock to handle said exception, which it does, otherwise you'll have an uncaught exception. It's not been rethrown fromExceptionsDemo, because its not being caught in the first place