捕获运行时异常?

use*_*806 2 java exception

我知道可以通过Exception catch块捕获RunTimeExceptions,如下所示.

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

我有自己创建的异常类,如下所示.

public class CustomException extends Exception {


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


    public CustomException(String message) {
        super(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是现在不是在catch块中保留Exception,而是保留了CustomException.But运行时异常现在没有被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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ani*_*kur 10

在此输入图像描述

扩展Exception类不会使它成为Runtime Exception.见上图.您还可以使用多态引用(超类)来捕获子类Exception.它反过来不起作用.


Dee*_*pak 5

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