为什么我在 Java 的异常处理中得到这个输出

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

任何人都可以向我解释这里发生了什么吗? 我得到的输出是

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

如果你想得到输出custom exception handling。您必须像这样

testCode 中抛出异常
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);
    }
}

当你捕捉到异常时,你可以再次抛出它。在您的原始代码中,您没有重新抛出异常,这就是为什么您只收到一条消息的原因。

你在testCode()方法中抛出MyOwnException对象,它立即被catch (Exception ex)捕获 这就是 System.out.print(" generic exception caught "); 被执行的原因,最终导致输出。