Try Catch Finally in C#

In c#, the try-catch-finally statement is useful to handle unexpected or runtime exceptions which will occur during execution of the program.

 

In try-catch-finally statement, the try block is used to hold the code that may cause an exception, catch block to handle exceptions and finally block is used to clean up or release any resources that are allocated in a try block. For example, close database connections or any streams or files that are opened in try block.

 

In c#, the finally block will always come after try or catch blocks and the finally block will always execute even if an exception occurred or not and it is useful to clean up or dispose of unmanaged objects based on the requirements.

C# try catch finally Syntax

Following is the syntax of handling errors in c# using try-catch-finally statement.

 

try

{

      // code that may cause exception

}

catch (Exception ex)

{

     // exception handling

}

finally

{

     // cleanup resources

}

As per the above syntax, the try block will contain the guarded code that may cause an exception so that if any errors occurred in our code, then immediately the code execution will be moved to catch block to handle those exceptions.

 

After completion of try or try & catch blocks, the finally block will always be executed even if an exception occurred or not and it is useful to clean up or release unmanaged resources.

 

In try-catch-finally statement, only one try & finally blocks are allowed but, we can use multiple catch blocks to handle different exception types.

 

In c#, the try block must always be followed by catch or finally or both blocks otherwise we will get a compile-time error.

C# try-catch-finally Example

Following is the example of handling exceptions in c# using try-catch-finally statement.

 

using System;

using System.IO;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            string fpath = @"D:\Test.txt";

            StreamReader sr = new StreamReader(fpath);

            try

            {

                string txt;

                while ((txt = sr.ReadLine()) != null)

                {

                    Console.WriteLine(txt);

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Exception: {0}", ex.Message);

            }

            finally

            {

                if (sr != null)

                {

                    sr.Close();

                }

            }

            Console.ReadLine();

        }

    }

}

If you observe the above code, we used try, catch and finally blocks to handle runtime or unexpected errors during execution of the program. Here, we wrote a code that may throw an exception inside of try block and in catch block we are handling the exception. As discussed, the finally block will execute after completion of try or catch block execution and release the required resources.

 

This is how we can use try-catch-finally blocks to handle unexpected or runtime exceptions based on our requirements.

 

PREVIOUS

Try Catch in C#
 
 

Topics Covered