Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
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;
In general there is nothing wrong with returning from a try-block. However it is good practice to keep blocks short, so having irrelevant code within a try block is not great.
Maybe the following is an improvement in your case:
// 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;
You probably cannot 'fix' the JedisConnectionException so I would either log (as shown above) or rethrow:
throw new MyAppException("Could not get result", e);
Don't log AND rethrow, it will give you and others headaches.
As mentioned you can also use try-with-resources in Java SE 7 if JedisConnection is a Closable:
try (JedisConnection jedis = Pool.getJedisConnection()) {
result = jedis.getResult(name);
} catch (JedisConnectionException e) {
LOG.error("Could not get result", e);
}
This will automatically close the JedisConnection after processing is done.
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
Even if you use return statement, the finally block would be executed.
The finally block would not be executed only when you call System.exit(0);
So, you can use your clean up code in finally block.
Using return however depends on other stuff like your solution design.
As long as finally really has to run even if !jedis.exists(name) evaluates to true, it's not only a good idea, it's practically a must. So for example, if you have a line like jedis.connect() (not real code, just an example), then the if should be inside the try, and finally should call jedis.disconnect. But if the code in your finally is fully dependent on what you would do after the check, then the if makes more sense before the try.
That depends, in your case it doesn´t matter, but as a general rule, consider this example:
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";
}
This might be somehow confusing, since the string returned is "this will be returned", no matter what finally was trying to do.
It is OK to reaturn a value from the try block.
Consider this case also in your implementation.
private static int testFinally() {
try {
return 100;
} finally {
return 101;
}
}
here the values are returned from try block and finally block. First it will execute the try block but before return it should execute the finally block. So this method will return 101, from the finally block instead of 100.
So returning from the finally block might produce unexpected results for the casual reader.
In my view
It is better to return values inside the Try block
Return the Default values/ appropriate values inside the Catch blocks in case of exceptions.
Only do the cleanups inside the finally block.
Related
In my code, I will attempt a certain task in a try-block. If exceptions are thrown, the catch-blocks will rectify the errors encountered (usually prompting for correct input). After that, the program is supposed to try again repeatedly until success is achieved. My current code is as follows:
for (bool isSuccess = false; !isSuccess;) {
try {
...
isSuccess = true;
}
// catch blocks here to correct any exceptions thrown
}
As can be seen, I'm currently using a loop structure to make the try-catch block start over if the try block fail, until the try block succeeds completely. Is there a more elegant solution?
I'd prefer to see a do loop that exits by default (then there is less chance of encountering an infinite loop). Your use of the boolean type only really mimics the behaviour of break and continue. As an alternative, perhaps more natural way, consider
do {
try {
// some code
} catch (/*whatever*/){
continue; // go again
}
break;
} while (true);
Just to give you an alternative, and if your code allows you to do so, then you could also use recursion. But in my eyes this is less favorable compared to the other ways to solve this.
public void doSomething() {
try {
...
} catch(Exception e) {
doSomething();
}
}
You can simple use a while loop.
while(!isSuccess){
try{
//DO Stuff
}
}
I think you should define a maximum of attempts. Otherwise in a worst scenario when all failures occur you app will be frozen.
You can do it with while loop
boolean isSuccess = false;
while(!isSuccess) { // loop till to isSuccess become true
try {
....
isSuccess = true;
} catch (Exception e) {
// Some Exception accrued, you can have 2 options
// 1. break the loop with break;
// 2. continue the process
}
}
You can also use recursion to do this. But I don't think it would be efficient. Do ... while would be the best approach.
I am fairly new to using try/catch blocks, so I don't know how exactly to perform this command.
If I catch an error, I would like to wait a period of time(10 seconds or so) then try to run the same line of code to attempt to continue in my try block. My program is written in Java. I have looked at both these pages: Page1, Page2, but neither of them are in Java. I have also looked at this, but they are not solving in the using the catch block. Is this possible to do, and how would I implement this in my catch block instead of just printing the error?
99% of time, you want to re-run a code-block after a try-catch and not the line with exception.
If you need to run from that line, than that is an indication for you to take your code in another method that encapsulates only that code (maybe move the try-catch there too).
What i would advice is something like this:
void method(){
try{
codeline1;
codeline2;
codeline3;
codeline4;
}
catch(Exception ex)
{
restorClassStateBeforeCodeLine1();
method();
}
}
By that snipped i propose to have your entire try-catch in a separate method.
Waiting random intervals is bad practice also. You never know if 10 seconds is right every time or at all.
Another way that I advise against would be:
label: {
try {
...
if (condition)
break label;
...
} catch (Exception e) {
...
}
}
It uses java labels to retry that part. I never tried but the break could be moved in the catch and the label in the try.
I don't think it is possible to return to a certain line in your try-block from inside a catch-block. Because when the throwis executed, the runtime system is going to pop frames from the call stack, looking for an exception handler to match the thrown exception and once the frame is popped from the stack, it's gone. More info about this can be found here
What you can do is call the method that caused the throw from within the catch-block. But that means it is going to execute your method from the beginning, so maybe you want to try to rearrange your code so that this does not cause any other problems. EDIT: The other answer demonstrates exactly what I mean.
This simple program loops through array values, testing each until it finds a value that doesn't generate an exception
public static void main(String[] args) {
int[] array=new int[]{0,0,0,0,5};
for(int i=0; i<array.length;i++) {
try {
System.out.println(10/array[i]);
break;
} catch(Exception e) {
try { Thread.sleep(1000); } catch(Exception ignore){}
}
}
}
while(true){
try{
//actions where some exception can be thrown
break;//executed when no exceptions appeared only
}
catch(YourException e){
Thread.sleep(10_000);
}
}
This cycle will be repeated while you instructions haven't executed. When code in try-block executed succesfully break helps you leave this cycle
Since you are saying that it is only 2 lines of code that you experience the intermittent error with, try something similar to this.
public static void main(String... args)
{
try
{
//Some Logic
//Error throwing logic in method
while(!doLogic())
{
Thread.sleep(1000);//Sleep here or in doLogic catch
}
//Continuing other logic!
}
catch(Exception e)
{
e.printStackTrace();
}
}
static Integer i = null;
public static boolean doLogic()
{
try
{
//Lines that throw error
System.out.println(i.toString());//NPE First run
}
catch (Exception e)
{
i = 1;
return false;
}
return true;
}
I have a simple doubt. In the following two codes, in first return statement is placed inside a finally block
public int method1(){
try{
// Some Stuff
} catch(Exception e){
e.printStackTrace();
} finally{
return 0;
}
}
And in second return statement is placed as normal
public int method1(){
try{
// Some Stuff
} catch(Exception e){
e.printStackTrace();
} finally{
}
return 0;
}
Is there any difference between these two? And which can be used as better option? why?
It is not a good practice to have "return" in a finally block. The finally block can be executed due to two reasons:
(a) An exception was thrown by the try block (and not caught by catch block) - in this case the method will have no return value so a return something statement in the finally block will have no effect.
(b) the try block completed normally. If that block ends with a return something then you the code is a bit confusing to the reader, as there are now two return statements that are relevant and it is not clear which should take precedence over the other.
This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Closed 9 years ago.
Given the following try/catch block in java:
try{
return;
}
catch(SomeException e){
System.out.println(e);
}
finally{
System.out.println("This is the finally block");
}
and according to this post: "Does finally always execute in Java?" I can see that the program's output will be 'This is the finally block'. However, I can't figure out how that would be possible since the print statement is preceded by a return...
I suspect that this behaviour has something to do with threading, however I am not certain. Please enlighten me. Thank you.
finally is executed before return statement. As java rule finally will always be executed except in case when JVM crashes or System.exit() is called.
Java Language Specification clearly mentions the execution of finally in different conditions:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2
return statement has no effect on the execution of finally block. The only way a finally block isn't executed is in case if JVM crashes/exits before executing finally block. Check this Link for more. So, if your code is replaced by
try{
System.exit(0);
}
catch(SomeException e){
System.out.println(e);
}
finally{
System.out.println("This is the finally block");
}
The finally block won't execute
Juned is correct. I also wanted to caution about throwing exceptions from finally blocks, they will mast other exceptions that happen. For example (somewhat silly example, but it makes the point):
boolean ok = false;
try {
// code that might throw a SQLException
ok = true;
return;
}
catch (SQLException e) {
log.error(e);
throw e;
}
finally {
if (!ok) {
throw new RuntimeException("Not ok");
}
}
In this case, even when an SQLException is caught and re-thrown, the finally throws a RuntimeException here and it it will "mask" or override the SQLException. The caller will receive the RuntimeException rather then the SQLException.
Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?
See the example below:
try {
// code that may or may not throw an exception
} finally {
SomeCleanupFunctionThatThrows();
// if currently executing an exception, exit the program,
// otherwise just let the exception thrown by the function
// above propagate
}
or is ignoring one of the exceptions the only thing you can do?
In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.
Set a flag variable, then check for it in the finally clause, like so:
boolean exceptionThrown = true;
try {
mightThrowAnException();
exceptionThrown = false;
} finally {
if (exceptionThrown) {
// Whatever you want to do
}
}
If you find yourself doing this, then you might have a problem with your design. The idea of a "finally" block is that you want something done regardless of how the method exits. Seems to me like you don't need a finally block at all, and should just use the try-catch blocks:
try {
doSomethingDangerous(); // can throw exception
onSuccess();
} catch (Exception ex) {
onFailure();
}
If a function throws and you want to catch the exception, you'll have to wrap the function in a try block, it's the safest way. So in your example:
try {
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) { //or catch whatever you want here
// exception handling code, or just ignore it
}
}
Do you mean you want the finally block to act differently depending on whether the try block completed successfully?
If so, you could always do something like:
boolean exceptionThrown = false;
try {
// ...
} catch(Throwable t) {
exceptionThrown = true;
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) {
if(exceptionThrown) ...
}
}
That's getting pretty convoluted, though... you might want to think of a way to restructure your code to make doing this unnecessary.
No I do not believe so. The catch block will run to completion before the finally block.
try {
// code that may or may not throw an exception
} catch {
// catch block must exist.
finally {
SomeCleanupFunctionThatThrows();
// this portion is ran after catch block finishes
}
Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.