-1

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);
    }
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142

2 Answers2

1

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.

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39
0

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.

elbraulio
  • 994
  • 6
  • 15