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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
vinod ep
  • 51
  • 1
  • 7
  • 1
    https://stackoverflow.com/questions/2274102/difference-between-using-throwable-and-exception-in-a-try-catch – litelite Jul 26 '17 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. – Henry Jul 26 '17 at 19:58
  • But given the code is passing exception, is there any value in having throwable? – vinod ep Jul 26 '17 at 20:11

2 Answers2

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

Florian
  • 140
  • 7
1

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.

Stijn Haezebrouck
  • 387
  • 1
  • 2
  • 14