Using return in a try block (Java)

I have a try block where they are trying to execute database queries, and a finally block in which database resources are released. If there is no value in the database, I return null.

Is it possible to return to the try block?

Code example:

    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
    }
+5
source share
7 answers

Is it possible to return to the try block?

Absolutely: if the preparation of the returned object is completely placed in the block area try, there is no reason to expand its visibility beyond its natural boundaries.

By way of illustration, this

try {
    ReturnType ret = ...
    // Compute ret
    return ret;
} catch {
    ...
} finally {
    ...
}

better than this

ReturnType ret = ...
try {
    // Compute ret
} catch {
    ...
} finally {
    ...
}
return ret;
+9
source

. finally , try. finally block readability . , , , .

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
+1

, try-. , , try .

, :

// assuming a String result type for sake of demonstration
String result = null;
if (jedis.exists(name)) {        
    try {
        result = jedis.getResult(name);
    } catch (JedisConnectionException e) {       
        LOG.error("Could not get result", e);
    } finally {
        jedis.close();
    }
}
return result;

, , "" JedisConnectionException, ( ), :

throw new MyAppException("Could not get result", e);

, .

, try-with-resources Java SE 7, JedisConnection Closable:

    try (JedisConnection jedis = Pool.getJedisConnection()) {
        result = jedis.getResult(name);
    } catch (JedisConnectionException e) {       
        LOG.error("Could not get result", e);
    } 

JedisConnection .

+1

return, finally .

finally System.exit(0);

, finally.

, , , .

0

, , , , !jedis.exists(name) true, , . , jedis.connect() ( , ), if try , , jedis.disconnect. , , .

0

, , , , :

String returnString="this will be returned";
try
{
    // ... something that could throw SomeException
    return returnString;
}
catch(SomeException ex)
{
    // Exception handling
}
finally
{
   returnString="this will not be returned";
}

- , - " ", , .

0

try.

.

private static int testFinally() {
        try {
            return 100;
        } finally {
            return 101;
        }
    }

try , , . try, finally. , 101 finally 100.

, finally .

Try

/ Catch .

finally.

0

All Articles