I have a function fun1(), which calls fun2(), which might throw an Exception :
public <T> T fun1(final String abc) throws XYZException {
try {
fun2()
} catch (final Exception e) {
throw new XYZException();
}
}
- If we are re-throwing the exception, does try catch make sense here?
- Should we add throws in the method definition line?
Well, you converting a general
Exceptionin the more specific oneXYZException. If this is the aim, it can make sense. Especially ifXYZExceptionis a user defined exception that helps to narrow the error down.On reason could be, that a other (more upper) error handler specifically catches the
XYZExceptionand handles it. While if it would have thrown the generalExceptionit does not know how to handle it.For Example: As fun1 is a generic function, if
fun1<Type1>("..")throws an XYZException you could for example try again withfun1<Type2>(".."). Both, fun1 and fun2 do not know what Type2 would be so they can't recover on their own.