1

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?

3
  • 1
    stackoverflow.com/questions/2274102/… Commented Jul 26, 2017 at 19:56
  • If you declare with Throwable you can pass in a Throawable that is not an Exception should you ever need to. Otherwise, there is little difference. Commented Jul 26, 2017 at 19:58
  • But given the code is passing exception, is there any value in having throwable? Commented Jul 26, 2017 at 20:11

2 Answers 2

2

You should not need to pass in a Throwable that is not an Exception. The only Throwables that are not Exceptions are Errors.

If you need to pass those in you constructor, it means that you need to have them catched first. Catching Errors 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 Exceptions, not Errors.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Good answer, though it lacks link to appropriate part of docs. Can you please add it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.