tags:

views:

352

answers:

8

Code A:

try{// Some Code}
catch{// Exception Handling code}
finally{// Clean up code}

Code B:

try{// Some Code}
catch{// Exception Handling code}
//clean up code

As far as I understand both the codes will serve the same purpose. Then why to have finally at all.

+3  A: 

Finally always gets executed, where as your code after the catch may not.

Sruly
why not! If the exception is handled properly the code will get executed definitly.
Nadeem
@Nadeem: See my answer for 3 reasons it may not happen.
Jon Skeet
+1  A: 

Because you need that code to execute regardless of any exceptions that may be thrown. For example, you may need to clean up some unmanaged resource (the 'using' construct compiles to a try/finally block).

Ed Swangren
+23  A: 
  • What happens if an exception you're not handling gets thrown? (I hope you're not catching Throwable...)
  • What happens if you return from inside the try block?
  • What happens if the catch block throws an exception?

A finally block makes sure that however you exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.

Jon Skeet
So, when do you sleep Jon? :)
Ed Swangren
Not necessarily true; finally won't get executed if (1) there's a `System.exit()` call (2) there's an infinite loop in the try or one of the catch block (3) I pull the plug on the computer
NullUserException
+1 for the System.exit()
Phobia
yeah they seem to be valid resons for having finally.
Nadeem
Can someone explain "What happens if you return from inside the return block"? Where is the return block?
TTT
@Alon try{ return 1;}finally{ retrun 2;}You will get 2
Dennis Cheung
@NullUserException: Hence the "modulo a few ways..." bit
Jon Skeet
@Alon: Typo, sorry - should have been "try block"
Jon Skeet
John Skeet lives here on stackoverflow, every question is like a doorbell ringing he has to answer :)
naikus
Oh, got it, thanks.
TTT
A: 

Code in the finally block will get executed no matter what. So if you have some database connections, or some other resources that need to be cleaned up, regardless of whether an exception happened, you would put that code in the finally block.

Adam
try{}catch{Exception e}//Database resource deallocation codeIn this case the deallocation code will execute regardless of the face whether the exception has occured or not.
Nadeem
@Nadeem: Not if the exception was an instance of Error instead of Exception. And catching Exception is pretty bad practice to start with...
Jon Skeet
A: 

finally ALWAYS executes,unless the JVM was shut down,finally just provides a method to put the cleanup code in one place

it would be too tedious if you had to put the clean up code in each of the catch blocks

Phobia
A: 

There may be times when you want to executea piece of code no matter what .. whether an exception is thrown or not .. over there one uses Finally ..

Egalitarian
+2  A: 

Note that (in Java at least, probably also in C#) it's also possible to have a try block without a catch, but with a finally. When an exception happens in the try block, the code in the finally block is run before the exception is thrown higher up:

InputStream in = new FileInputStream("somefile.xyz");
try {
    somethingThatMightThrowAnException();
}
finally {
    // cleanup here
    in.close();
}
Jesper
A: 

You may want to put the code that you want to anyway get executed irrespective of what happens in your try or catch block. Also if you are using multiple catch and if you want to put some code which is common for all the catch blocks this would be a place to put- but you cannot be sure that the entire code in try has been executed. e.g. conn c1 = new connection(); try{ c1.dosomething(); }catch (ExceptionA exa){ handleexA(); //c1.close(); }catch (ExceptionB exb){ handleexB(); //c1.close(); }finally{ c1.close(); }

Balaji Natesan