我知道可以通过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)
谢谢!
这是因为CustomException不是超级类RuntimeException.因为你正在抛出RuntimeException,而不是它的子类CustomException,所以catch块没有捕获它.
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |