Java 捕获运行时异常?

Java 捕获运行时异常?,java,exception,Java,Exception,我知道运行时异常可以被异常捕获块捕获,如下所示 public class Test { public static void main(String[] args) { try { throw new RuntimeException("Bang"); } catch (Exception e) { System.out.println("I caught: " + e); } } }

我知道运行时异常可以被异常捕获块捕获,如下所示

public class Test {
    public static void main(String[] args) {
        try {
            throw new RuntimeException("Bang");
        } catch (Exception e) {
            System.out.println("I caught: " + e);
        }
    }
}
public class CustomException extends Exception {


    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }


    public CustomException(String message) {
        super(message);
    }
}
我创建了自己的异常类,如下所示

public class Test {
    public static void main(String[] args) {
        try {
            throw new RuntimeException("Bang");
        } catch (Exception e) {
            System.out.println("I caught: " + e);
        }
    }
}
public class CustomException extends Exception {


    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }


    public CustomException(String message) {
        super(message);
    }
}
但现在,我并没有将异常保留在catch块中,而是保留了CustomException。但运行时异常现在并没有被catch块捕获。为什么?

public class Test {
        public static void main(String[] args) {
            try {
                //consider here i have some logic and there is possibility that the logic might throw either runtime exception or Custom Exception
                throw new RuntimeException("Bang");
            } catch (CustomException e) {
                System.out.println("I caught: " + e);
            }
        }
    }

谢谢

这是因为
CustomException
不是
RuntimeException
的超类。因为您正在抛出
RuntimeException
,它不是
CustomException
的子类,所以catch块没有捕获它。


扩展异常类不会使其成为运行时异常。见上图。还可以使用多态引用(超类)捕获子类异常。相反,它不起作用。

无需在标题中再次编写java,java标记就足够了,因为他们说
一幅图能画出千言万语
RuntimeException不是一个包罗万象的类,一个异常是,或者可能是一个可丢弃的类,但这三个类都是具体的类,不提供“包罗万象”接口。是的,755806但CustomException不扩展RuntimeException,它们有不同的契约。