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
}
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With