11

What is the difference between "finally" and write after "catch"?

For example:

public boolean example() {
    try {
        // Code
    } catch (RuntimeException e) {
        // Code
    } finally {
        return true;
    }
}

public boolean example() {
    try {
        // Code
    } catch (RuntimeException e) {
        // Code
    } 
    return true;
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Milton90
  • 547
  • 2
  • 7
  • 15
  • You could add logic to close the resources in the `finally` block statement and get an exception here, so the best alternative would be the latter (IMO). – Luiggi Mendoza Jun 23 '13 at 14:41
  • no difference in your example. Do some cleanup in finally which will be executed anyway. – Tala Jun 23 '13 at 14:43

10 Answers10

8

First of all, the only idiom that can even be considered a candidate is this:

try {
    // stuff
} catch (Throwable t) { 
    // handle
}
// finally stuff

Note the caught type. Only if you catch any possible exception, including such dark monsters as ThreadDeath and VirtualMachineError can you hope to unconditionally reach the code below the try-catch.

But, that's only where it begins. What if the handling code itself throws an exception? So you need at least

try { 
    // main stuff
} catch (Throwable t) {
    try { 
        // handle 
    } catch (Throwable t) { 
        // no code allowed here! Otherwise we descend into
        // infinite recursion
    }
}
// finally stuff

Now you may be beginning to realize the benefits of finally, but that's not all. Consider a quite typical scenario:

try { 
  // main stuff, may throw an exception. I want the exception to
  // break what I'm doing here and propagate to the caller.
  return true;
} finally { 
    // clean up, even if about to propagate the exception 
}

How do you rewrite this? Without code duplication, impossible.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
3

In the code you have provided there is no difference. But finally is used to run some piece of code after the try block no matter whether there is an exception or not.

Interesting point to make here is, we should avoid to return from the finally block because it can create confusion in scenarion when we return something from try block as well. Consider this piece of code:

try {
    return true;
}
finally {
    return false;
}

Now this code will return false no matter what happens in try. In many ways this behaviour is exactly consistent with the colloquial understanding of what finally means - "no matter what happens beforehand in the try block, always run this code." Hence if you return true from a finally block, the overall effect must always to be to return true, no?

In general, this is seldom a good idiom, and you should use finally blocks liberally for cleaning up/closing resources but rarely if ever return a value from them.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • If finally terminates abruptly, by return or by throwing an exception, any previous return of the function call is ignored. This means that finally will swallow any exception or ordinary return value, if it throws an exception or you uses return. As stated only use finally for resource cleanup, and be aware that if you make calls in finally that could throw an exception, you should wrap them in try-catch to avoid swallowing other exceptions. If you use try-with-resources you can get the swallowed exception with Throwable.getSuppressed() – Klaus Groenbaek Dec 13 '16 at 09:54
2

No difference in Your case. but

The runtime system always executes the statements within the finally block regardless of what happens within the try block.

So it's the perfect place to perform cleanup.

Note that if you're using JDK 7+, then most uses of the finally block can be eliminated, simply by using a try-with-resources statement.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

We use try block, catch block and finally block to handle Exception in our program. A program may be have check or unchecked Exception. so this block are are used to handle those Exception. In the try block we mention or write those code which may be cause of an Exception and if we want that our code will be run if Exception occurred Then we write those code in the catch block. finally is a very special block which give us a special feature that if our catch block doesn't run then before the program goes to terminate that finally block code definitely execute. mostly this is use to save our data during unwanted program termination. if we use try block then there must be a catch block after the try block but finally is an optional not compulsory.

0

First thing to understand in this question is "why we use try{ } catch{ } block" Ok.

The answer is,when there is a possibility of our code of throwing an exception.

These kind of code we put in try{... } block & catch {...} block contain the code to catch the exception generated by code in try{ } block.

Finally{...} block contain the code executed immediately after try{} catch{} block when try{ } block throws an exception.

e.g When you visit some website,but do to some server side problem it couldn't and page display some kind of message like "404 error or server is updating",these kind of code is written in finally block.

Aamir
  • 143
  • 10
0

this simple catch only is for catch eXception and process it, but finally, execute if Exception or not , for example for close connections.

0

Finally block is useful to cleanup your code like closing open streams.

E.g:

    File f = new File("\file.txt");
    FileStream fs;
    try{
       fs = new FileStream(f);
    } catch (IOException ioe){
       ioe.printStackTrace();
    } finally {
      if (fs != null) {
         fs.close() // close the stream
      }
    }
Ashish Patel
  • 163
  • 6
0

As your code only returning true/false , so it won't impact much . But think for any other code/logic where some mandatory/cleanup code is written to execute.

Also, it will difficult to catch all the exceptions via our code or in other words, we should catch specific exceptions which we can handle. At that point , finally will be real savior, as it will always execute(other than System.exit() or in some recursion case).

Also, for bringing the consistency in our code, one should always use finally block to perform any clean up code.

You may refer the below posts too for more clarification:

Community
  • 1
  • 1
dildeepak
  • 1,349
  • 2
  • 16
  • 34
0

First Case:

If exception occurred in try block then catch block would be executed, and while serving the same catch block if there is again exception occurred then finally block would execute.

Second Case:

If exception occurred in try block then catch block would be executed, and if there is further exception in the same catch block then "return true;" would execute.

Nilesh Jadav
  • 890
  • 9
  • 8
-2

finally() is used whenever we want that some line of code should be executed even if exception occurs But if u write line of code after catch it will not execute if exception occurs..

EduardoSaverin
  • 545
  • 4
  • 19