Finally block

suggest change
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:

Feedback about page:

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


Exception Handling:
* Finally block

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
74 Exception Handling
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script