Finally block C# with Example
/* code that could throw an exception */
/* handle the exception */
/* 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 ﬁles.
FileStream f = null;
f = File.OpenRead("file.txt");
/* process the file here */
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 ﬁnally block will be executed.
In the ﬁle-reading we could have used a using block as FileStream (what OpenRead returns) implements
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:
When a StackOverﬂow occurs.
The application process is killed, usually by an external source.