简体   繁体   中英

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. (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...

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(); condition all the time.

how can I handle this situation and execute my do.somethingProgramaticalError(); condition ???

You should never throw an instance of Exception (or its unchecked child 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. 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. This will be the case for the vast majority of exceptions you run into.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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