I'm adding Exception handling to my Java application and don't understand why in some cases the String returned by Exception methods e.getMessage()
or e.getLocalizedMessage()
includes the package of my custom Exception class.
This is how I have it configured:
MyCustomException:
package project.be.exception;
public class MyCustomException extends Exception{
public MyCustomException() {
}
public MyCustomException(String arg0) {
super(arg0);
}
public MyCustomException(Throwable arg0) {
super(arg0);
}
public MyCustomException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public MyCustomException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
}
}
MyServiceCaller:
public class MyServiceCaller implements HISException DefaultRESTService<DefaultModel>{
public DefaultResponse get(Service_Api service, Object caller, Object param) throws MyCustomException {
try{
...
} catch (Exception e){
throw new MyCustomException ("Hello message exception");
}
}
}
MyBussinessClass:
...
try{
new MyServiceCaller().get(service, param1, param2);
} catch(MyCustomException e){
System.out.println(e.getLocalizedMessage());
}
...
Console output:
project.be.exception: Hello message exception
I want to print only the message without previous the package. Any suggestion?
Edit1:
The output is the same using Exception.getMessage(), thus I discard possible duplication with question: Difference between e.getMessage() and e.getLocalizedMessage()
SOLUTION:
As isaac mentioned, I'm wraping the thrown exception in another and by this reason e.getMessage()
and e.getLocalizedMessage()
shows the package.
In my case solve the output was easy calling e.getCause().getMessage()
instead of e.getMessage()
and e.getLocalizedMessage()
.
MyCustomException
is missing. Also do you overridegetMessage()
orgetLocalizedMessage()
?