简体   繁体   English

捕获运行时异常?

[英]Catching run time exceptions?

I know that RunTimeExceptions can be caught by Exception catch block as below. 我知道可以通过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);
        }
    }
}

I have my own created exception class as below. 我有自己创建的异常类,如下所示。

public class CustomException extends Exception {


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


    public CustomException(String message) {
        super(message);
    }
}

But now instead of keeping Exception in catch block, i kept CustomException.But run time exception is not caught by catch block now. 但是现在不是在catch块中保留Exception,而是保留了CustomException.But运行时异常现在没有被catch块捕获。 Why? 为什么?

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

Thanks! 谢谢!

在此输入图像描述

Extending Exception class does not make it is Runtime Exception. 扩展Exception类不会使它成为Runtime Exception。 See above diagram. 见上图。 Also you can use polymorphic reference(superclass) to catch an subclass Exception. 您还可以使用多态引用(超类)来捕获子类Exception。 It does not work the other way around. 它反过来不起作用。

This is because CustomException is not a super class of RuntimeException . 这是因为CustomException不是RuntimeException的超类。 Because you are throwing RuntimeException , which is not the subclass of CustomException , the catch block is not catching it. 因为你抛出的RuntimeException不是CustomException的子类,所以catch块没有捕获它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM