Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where the finally is necessary?

I know how to use try-catch-finally. However I do not get the advance of using finally as I always can place the code after the try-catch block. Is there any clear example?

like image 415
Tray13 Avatar asked Feb 11 '11 13:02

Tray13


People also ask

Why finally is needed?

Why finally Is Useful. We generally use the finally block to execute clean up code like closing connections, closing files, or freeing up threads, as it executes regardless of an exception. Note: try-with-resources can also be used to close resources instead of a finally block.

What is finally and where do we use it?

The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.

Why the finally is needed in Java?

But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return , continue , or break . Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Why is finally needed in try catch?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.


1 Answers

It's almost always used for cleanup, usually implicitly via a using statement:

FileStream stream = new FileStream(...);
try
{
    // Read some stuff
}
finally
{
    stream.Dispose();
}

Now this is not equivalent to

FileStream stream = new FileStream(...);
// Read some stuff
stream.Dispose();

because the "read some stuff" code could throw an exception or possibly return - and however it completes, we want to dispose of the stream.

So finally blocks are usually for resource cleanup of some kind. However, in C# they're usually implicit via a using statement:

using (FileStream stream = new FileStream(...))
{
    // Read some stuff
} // Dispose called automatically

finally blocks are much more common in Java than in C#, precisely because of the using statement. I very rarely write my own finally blocks in C#.

like image 97
Jon Skeet Avatar answered Oct 16 '22 02:10

Jon Skeet