If you want to aviod reflection at all costs, you will have to pay for this. The presented solution will sacrifice precision w.r.t. the type of the Throwable
. To append something to the message, we will wrap the given Throwable
in an Exception
by deploying the constructor Exception(String, Throwable)
public static <T extends Throwable> Exception withExclamationMark(T t) {
return new Excpetion(t.getMessage() + "!", t);
}
As I already mentioned, this method only returns instances of the class Exception
, thus when you try to catch
those Exception
s, you would have to check the cause
:
try {
...
} catch (Exception e) { // let's assume you would normally catch an IOException here
Exception cause = e.getCause();
if ((cause != null) && (cause instanceof IOException) {
IOException ioEx = ((IOExcpetion) cause);
// handle excpetion
} else {
throw e; // or System.exit(42) or halt and catch fire or ...
}
}
For a solution deploying reflection, please see @sanit's answer. Maybe a combination of both answers could lead to a satisfying solution.