Why i'm getting this output in exception handling in Java

73 Views Asked by At

Can anybody explain to me what is happening here? Output I'm getting is

generic exception caught

public class TestingString {
    static void testCode() throws MyOwnException {
        try {
            throw new MyOwnException("test exception");
        } catch (Exception ex) {
            System.out.print(" generic exception caught ");
        }
    }
    public static void main(String[] args) {
        try {
            testCode();
        } catch (MyOwnException ex) {
            System.out.print("custom exception handling");
        }
    }

}

class MyOwnException extends Exception {
    public MyOwnException(String msg) {
        super(msg);
    }
}
2

There are 2 best solutions below

1
elbraulio On BEST ANSWER

if you want to get the output custom exception handling. You have to throw the exception in testCode like this

public class TestingString {
    static void testCode() throws MyOwnException {
        try {
            throw new MyOwnException("test exception");
        } catch (Exception ex) {
            System.out.print(" generic exception caught ");
            // throw the exception!
            throw ex;
        }
    }
    public static void main(String[] args) {
        try {
            testCode();
        } catch (MyOwnException ex) {
           System.out.print("custom exception handling");
        }
    }
}

class MyOwnException extends Exception {
    public MyOwnException(String msg) {
        super(msg);
    }
}

when you catch the exception you can throw it again. In your original code you are not re-throwing the exception, that is why you only got one message.

0
ZhaoGang On

You throw the MyOwnException object in the testCode() method, which is caught immediately by catch (Exception ex) that is the reason why System.out.print(" generic exception caught "); is excuted , which finally leads to the output.