ARTICLE

Try-Finally in C#

Posted by Puran Mehra Articles | C# Language December 20, 2009
In this article I will explain you about Try-Finally in C#.
Reader Level:

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.

Login to add your contents and source code to this article
post comment
     
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter