Reputation: 9
Is it possible to make something like that?:
try {
...
} catch (exception){
return; // this is most important thing here. In catch block only "return"
}
Can I handle exception in this way - use only "return;"? It works fine, but I would like to know is it correct?
Upvotes: 1
Views: 69
Reputation: 1863
if you do something like this
public void someMethod(){
try{
...
} catch (Exception e) {
return;
}
}
You lose your exception.It's a bad practice, because if something goes wrong - you even won't be able to understand what's going wrong. Better ways
Upvotes: 0
Reputation: 31
It is correct syntax but as per java coding standards we must not swallow exceptions rather handle them in catch block or rethrow it with proper message
Upvotes: 1
Reputation: 45319
Yes, that's actually a valid use case. There are many valid reasons to return in the catch block, one of them being returning default values:
try {
return service.getData();
} catch (SocketTimeoutException ex) {
logTimeout(ex);
return getCachedData();
}
Upvotes: 1
Reputation: 120848
This way you are ignoring the Exception
, is it really want you want? It all depends on your context - it might be safe to do this (I doubt it, but hey, it's your code). Generally when some Exceptions happens - you should react, not by simply return
ing, but logging, defaulting (rarely a good option), retrying, etc.
Upvotes: 3