Master1ek
Master1ek

Reputation: 9

Return in try catch block. Correcty?

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

Answers (4)

Danila Zharenkov
Danila Zharenkov

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

  • print error message to logs
  • rethrow this exception or your custom exception and process it on the next levels

Upvotes: 0

Payal Gupta
Payal Gupta

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

ernest_k
ernest_k

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

Eugene
Eugene

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 returning, but logging, defaulting (rarely a good option), retrying, etc.

Upvotes: 3

Related Questions