Reputation: 51
Let's say I'm writing a custom exception class in Java. What's the difference between the two constructors? In what scenario would I want to use one and the other?
class CustomException extends Exception{
public CustomException(String msg);
public CustomException(String msg, Throwable cause);
or
public CustomException(String msg, Exception ex);
}
Code block this customException once it catch other exceptions that happens in remote call.
} catch(Exception1 | Exception2 | Exception3 ex){
throw new CustomException("custom", ex)
}
Is making Throwable give us a flexibility ? Given the code is only catching exception, is there a difference?
Upvotes: 1
Views: 1424
Reputation: 140
You should never catch/handle Throwables which are not Exceptions. For more info refer to the Java Documentation.
Edit: Every Throwable, which is not an Exception is an Error. Errors are unusual states, which should never happen.
Links: https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
Upvotes: 1
Reputation: 397
You should not need to pass in a Throwable
that is not an Exception
. The only Throwable
s that are not Exception
s are Error
s.
If you need to pass those in you constructor, it means that you need to have them catched first. Catching Error
s is generally bad, as, according to the java api , it represents serious problems that a reasonable application should not be able to catch. Errors are mostly errors caused deeply in the JVM, and you cannot do anything about it. Probably, you JVM will be corrupted, so handling them is not reliable anymore. And you should certainly not try to convert errors to exceptions.
So those signatures are fine:
public CustomException(String msg, Exception cause);
public CustomException(String msg);
but this one is pointless:
public CustomException(String msg, Throwable cause);
because all causes you want to catch and propagate are Exception
s, not Error
s.
Upvotes: 2