The try..catch..finally block in .NET allows developers to handle runtime exceptions. The syntax has three variations, try..catch, try..finally, and try..catch..finally. Learn more here:
Exception Handling in C#
The code example shows a try catch finally block syntax.
- try
- {
- }
- catch
- {
-
- }
- finally
- {
-
-
-
-
-
-
-
- }
Let's go through an example so that we can better understand the purpose of the finally block. The following code illustrates the use of the finally block to clean up file states.
- namespace TestFinally
- {
- using System;
- using System.IO;
-
-
-
- public class TestFinally
- {
- public TestFinally()
- {
-
- }
- public static void Main()
- {
- StreamReader sr1 = null;
- StreamWriter sw1 = null;
- try
- {
- System.Console.WriteLine("In try block");
-
- sr1 = new StreamReader(File.Open("Test1.txt",
- System.IO.FileMode.Open));
- sw1 = new StreamWriter(File.Open("Test2.txt",
- System.IO.FileMode.Append,
- FileAccess.Write));
- while (sr1.Peek() != -1)
- {
- sw1.WriteLine(sr1.ReadLine());
- }
- goto MyLabel;
- }
- catch (Exception e)
- {
- Console.WriteLine(String.Concat(e.Message,
- e.StackTrace));
- }
- finally
- {
-
-
-
-
-
-
- Console.WriteLine("In finally block");
-
-
-
-
-
-
- if (sr1 != null)
- {
- sr1.Close();
- }
- if (sw1 != null)
- {
- sw1.Close();
- }
- }
- MyLabel:
- Console.WriteLine("In Mylabel");
-
-
-
- Console.ReadLine();
- }
- }
- }
In the above code, inside the Main method, we opened two files. First we opened the Test1.txt using a StreamReader object by passing a FileStream object returned by the File.Open method, and then we opened Test2.txt through a StreamWriter object by passing a FileStream object returned by the File.Open method. The intention here is to copy lines of Test1.txt and append them to Test2.txt. If the code in the try block executes successfully, we want to close StreamReader sr1 and StreamWriter sw1 so that system resources associated with the reader/writer are released.
If Test1.txt opens successfully but for some reason there is an exception thrown while opening Test2.txt, we still want to close the stream associated with Test1.txt. So in this example we have added the close methods in the finally code block so that they can be positively executed. We are checking for a null value because if none of the files is opened, we would get a nulldereferencing exception in the finally block.
Conclusion
Hope this article helped you understand how to use the try..catch..finally block in C#.