Essential C# Exception Handling  Suggest an edit

Finally block

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

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. However, since there is no catch block, the execution will cause termination. Before termination, the statements inside the finally block will be executed.

In the file-reading we could have used a using block as FileStream (what OpenRead returns) implements IDisposable.

Even if there is a return statement in try block, the finally block will usually execute; there are a few cases where it will not:


Table Of Contents
22 Enum
25 GUID
75 Exception Handling
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close