Finally block

suggest change
try
{
    /* code that could throw an exception */
}
catch (Exception)
{
    /* handle the exception */
}
finally
{
    /* Code that will be executed whether or not an exception was thrown or caught */
}

The try / catch / finally block can be very handy when reading from files.

For example:

FileStream f = null;

try
{
    f = File.OpenRead("file.txt");
    /* process the file here */
}
finally
{
    f?.Close(); // f may be null, so use the null conditional operator.
}

A try block must be followed by either a catch or a finally block. The file example has no catch, so an exception from OpenRead still propagates after the finally block runs.

The file example could instead use a using block, because the FileStream returned by OpenRead implements IDisposable.

A return inside the try block still runs the finally block in ordinary cases. finally does not run in a few cases:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents