Try-Finally in C#


This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

If you are interested in executing a certain block of code irrespective of whether an exception occurs and you do not worry about catching an exception, then you'll likely want to use the try-finally statement. However, we do not recommend using this statement because you will not be able to see what the exception is about. Instead, you should use the try-catch-finally statement. Listing 7.8 shows the structure of the Try-Finally block:

Listing 7.8: Try-Finally Syntax

            try
            {
                //Even if a goto statement were here
                //control gets transferred to the statement identified in
                //goto statement only after executing the finally block.
            }

            finally
            {
                // This block of code will always get executed
                // whether an exception occurs or not
                // Any cleanup code goes here,
                // especially to release any system resources
                // such as file handles and network connections
            }


First the try block is executed, and then the finally block is executed, irrespective of whether an exception occurs or not. Even if a goto statement is present in the try block, the control gets transferred to the label in the goto statement only after executing the finally block.

Conclusion


Hope this article would have helped you in understanding Try-Finally in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all
    Learn
    View all