Home > Blockchain >  Catching an error that I dont want to catch
Catching an error that I dont want to catch

Time:12-17

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");
            }
        }
     }

CodePudding user response:

This happens because in your show() method, you are catching a specific type of exception called InsufficientFundsException. But the exception thrown by account.deposit() is IOException which is caught only in your main method. That is why the catch in the main method gets executed and not the catch in ExcpetionsDemo

If you want to catch IOException in your ExceptionsDemo class you can do this:

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()); 
    }
}

A single try block can have multiple catch blocks for each type of exception and the handling of each exception can be customized to what you want by coding it in each of their catch blocks.

CodePudding user response:

Your ExceptionsDemo throws a IOException, your catch in ExceptionsDemo only catches a InsufficientFundsException so it will not be caught in the ExceptionsDemo, it will bubble to the caller, and be caught there, providing there is a catch block to handle said exception, which it does, otherwise you'll have an uncaught exception. It's not been rethrown from ExceptionsDemo, because its not being caught in the first place

CodePudding user response:

try {
    // do what you want
} catch (InsufficientFundsException e) {
    // catch what you want
} catch (Exception e) {
    // catch unexpected errors, if you want (optional)
}
  • Related