Reputation: 23257
I'd like to know what is the best way or best-practice to handle this kind of situation. Guess a straightforward function like this:
public Object f1() {
Object result = null;
try {
String payload = methodThrowsAnException();
result = payload;
} catch (IOException e) {
throw new IllegalStateException(e); <<<<<<<<<<<<<<<
}
return result;
}
I'd like to know if it's a good practice:
re-throw
the exception ornull
when something has been wrong inside.I don't know if I've explained so well.
Upvotes: 1
Views: 67
Reputation: 4243
There is nothing wrong with returning a null from your method if there is a particular scenario where you expect that exception.
Alternatively you can just allow the Exception to bubble up, and be handled by the caller.
When would I catch and re-throw an exception? When I can convey better meaning by throwing a new exception.
Would I include the original exception when I throw a new one? I would do it if it is a unknown/unexpected scenario which requires further debugging.
Let me share some examples:
FileNotFoundException
and instead I will throw a BackupFileMissingException
which is specific to my application. Here I don't need to include the FileNotFoundException
because it is an expected scenario and there is nothing further to investigate.InterfaceApiException
and include the original exception, so that it can be logged at the REST/Action layer along with the root cause.Upvotes: 0
Reputation: 15852
Re-throwing caught exception is a bad idea. most often, the stacktrace will contain more or less detailed information about your architecture. This would be to useful for an attacker.
I wouldn't allow my app to get into illegal state because of the user's action. In your case, I would say:
try {
String payload = methodThrowsAnException();
result = payload;
} catch (IOException e) {
throw new IllegalArgumentException(<user's input which caused the exception>); <<<<<<<<<<<<<<<
}
Upvotes: 1