简体   繁体   English

java.lang.exception.getCause() 每次都为 null

[英]java.lang.exception.getCause() gets null every time

In one of the softwares that I develop, I am trying to manage an exception mechanism.在我开发的其中一个软件中,我试图管理异常机制。

At somewhere of the programme, I do something like;在程序的某个地方,我做了类似的事情;

IF(my condition not allowed){
    throw new Exception("My condition not allowed", null)
}

I throw null with the parameter of java.lang.exception to understand that this is something not relevant with a programatical error.我使用 java.lang.exception 的参数抛出 null 以了解这与程序错误无关。 (I don't have a chance to create my own custom exception, please consider that) (我没有机会创建自己的自定义异常,请考虑)

And in the somewhere above the programming I catch my exception like this;在程序上方的某个地方,我捕获了这样的异常;

}catch(Exception e){
if(null == e.getCause)
    do.somethingThatIWantToCatch();
}else{
    do.somethingProgramaticalError();
}

here the problem is;这里的问题是; my code may throw something else that I don't know like NullPointerException, ArrayIndexOutOfBoundsException etc...我的代码可能会抛出一些我不知道的东西,比如 NullPointerException、ArrayIndexOutOfBoundsException 等......

At this point I expect that e.getCause() should NOT be null if I get programatical error, however I get NULL all the time and I execute my do.somethingThatIWantToCatch();在这一点上,我希望 e.getCause() 不应该为 null,如果我遇到编程错误,但是我总是得到 NULL 并执行我的 do.somethingThatIWantToCatch(); condition all the time.状态一直。

how can I handle this situation and execute my do.somethingProgramaticalError();我该如何处理这种情况并执行我的 do.somethingProgramaticalError(); condition ???健康)状况 ???

You should never throw an instance of Exception (or its unchecked child RuntimeException ).永远不应该抛出Exception的实例(或其未经检查的子RuntimeException )。 You should always find an appropriate subclass to throw, or create your own subclass if there isn't already a suitable one.您应该始终找到一个合适的子类来抛出,或者如果还没有合适的子类,则创建自己的子类。

Catching Exception will catch every type of exception under the sun, including the NullPointerException that you're concerned about and other exception types that you're not.捕获Exception将捕获阳光下的所有类型的异常,包括您关心的NullPointerException和您不关心的其他异常类型。 It is always best to be as specific as possible about the type of exceptions you catch, so that these other ones you don't want to inadvertently handle are not handled.最好尽可能具体地说明您捕获的异常类型,以便不会处理您不想无意中处理的其他异常。

As for getCause() , that is generally an exception that is passed into the constructor of another exception.至于getCause() ,这通常是传递到另一个异常的构造函数中的异常。 This will be the case for the vast majority of exceptions you run into.您遇到的绝大多数例外情况都是如此。

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

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