Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return from method, in the "try" block or after "catch" block?

Is there any difference between following two methods?

Which one is preferable and why?

Prg1:

public static boolean test() throws Exception {
    try {
        doSomething();
        return true;
    } catch (Exception e) {
        throw new Exception("No!");
    }    
}

Prg2:

public static boolean test() throws Exception {
    try {
        doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    return true;    
}
like image 599
EbraHim Avatar asked May 01 '16 10:05

EbraHim


3 Answers

Consider these cases where you're not returning a constant expression:

Case 1:

public static Val test() throws Exception {
    try {
        return doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    // Unreachable code goes here
}

Case 2:

public static Val test() throws Exception {
    Val toReturn = null;
    try {             
        toReturn = doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    return toReturn;
}

I would prefer the first one. The second is more verbose and might cause some confusion when debugging.

If test() incorrectly returns null, and you see toReturn being initialized to null, you might think the problem is in test() (especially when test() is not just a simple example like this).

Even though it can only return null if doSomething returns null. But that might be hard to see at a glance.


You could then argue that, for consistency's sake, it's better to always use the first form.

like image 93
Jorn Vernee Avatar answered Nov 19 '22 04:11

Jorn Vernee


Nope there is no difference between both the methods. It will return true value in both the cases effectively by resuming the flow of the program as soon an and exception is handled. Catch will be accessed only when an exception occurs.

like image 45
rvp_15 Avatar answered Nov 19 '22 06:11

rvp_15


I'm assuming this is a general question. Otherwise I might comment on other aspects of your method(s).

I think in the case or small methods like these it doesn't really matter. The method is short enough to understand immediately what's going on, what's related to what etc.

However, in the case of longer methods the flow is much easier to follow in the first example. In my opinion. It keeps together related code and related scenarios. When you're reading the method, the normal execution flow is not broken by the catch block, making it more obvious and "fluent".

public static boolean test() throws Exception {
    try {
        doSomething();
        return true;
    } catch (Exception e) {
        throw new Exception("No!");
    }    
}

But I won't generalize this for all methods; it's all about the context.

like image 2
async Avatar answered Nov 19 '22 06:11

async