Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using return in try block (Java) [closed]

Tags:

java

I have a try block where database queries are attempted to be run and a finally block where database resources are released. If a value does not exist in the database I return null.

Is it a good idea to return in a try block?

Some example code:

    try {
        if (!jedis.exists(name)) {
            return null; // Is this a good idea?
        }

        // Do database related stuff...
    } catch (JedisConnectionException e) {
        // Fix any problems that happen
    } finally {
        // Return all objects to pools and clean up
    }
like image 312
user2248702 Avatar asked Jul 23 '14 11:07

user2248702


2 Answers

Is it a good idea to return in a try block?

Absolutely: if the preparation of an object to be returned fits entirely within the scope of the try block, there is no reason to extend its visibility beyond its natural boundaries.

As an illustration, this

try {
    ReturnType ret = ...
    // Compute ret
    return ret;
} catch {
    ...
    // need to either throw or return something
} finally {
    ...
}

is better than this

ReturnType ret = ...
try {
    // Compute ret
} catch {
    ...
} finally {
    ...
}
return ret;
like image 132
Sergey Kalinichenko Avatar answered Nov 09 '22 11:11

Sergey Kalinichenko


Consider this example. finally block will be executed even if you return in the try block. Its better to return in the finally block for better readability of code . You can trace from where your value is being returned, else you might end up with some problems figuring that out.

public static void main(String[] args) {
        System.out.println(someMethod());
    }

    private static boolean someMethod() {
        try {
            System.out.println("in try");
            return true;
        } catch (Exception e) {

        } finally {
            System.out.println("in finally");
            return false;
        }

    }

O/P :

in try
in finally
false -- > not true, but false
like image 40
TheLostMind Avatar answered Nov 09 '22 11:11

TheLostMind