In java, why custom exceptions should also have a constructor with arg argument like "Throwable cause"

Can someone explain why we should have constructors, for example below, when defining custom exceptions:

public MyException(Throwable cause) {
    super(cause);
}

public MyException(String message, Throwable cause) {
    super(message, cause);
}
+4
source share
2 answers

It allows you to add a reason for the exclusion of this exception to your custom instance information for the exception.

This is useful if you catch one exception and throw another.

For instance:

try {
    ....
}
catch (SomeException ex) {
    throw new MyException ("some message", ex);
}
+3
source

, MyException, Exception . .

, Throwable :

public MyException() {
    super();
}

public MyException(String message) {
    super(message);
}

. : , MyClass:

public static void myMethod() throws MyException{
   //Some code
}

myMethod() :

try{
   MyClass.myMethod();
} catch (MyException e){
   e.getCause();
}

, , e.getCause() null. , .

+1

All Articles