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?
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.
The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.
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.
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.
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#.
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