C# Exception Handling

As we learned in previous c# exception topic, exceptions are generated by CLR (common language runtime) or application code. To handle runtime or unexpected errors in applications, c# has provided a built-in exception handling support by using try, catch and finally blocks.

 

In c#, when an exception is thrown, then the CLR (common language runtime) will look for the catch block that handles the exception. In case, if currently executing method does not contain such a catch block, then the CLR will display an unhandled exception message to the user and stops the execution of the program.

 

Following is the syntax of handling errors in c# using try, catch and finally blocks.

 

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. In case, if no exception occurred in the try block, then the catch block will be skipped and the execution will be moved to finally block.

 

After completion of try or try & catch blocks, 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.

 

In c#, the try block must be followed by catch or finally or both blocks otherwise we will get a compile-time error. In a try-catch-finally statement, only one try & finally blocks are allowed but we can use multiple catch blocks to handle different exception types.

C# Exception Handling Example

Following is the example of handling exceptions in c# using try, catch and finally blocks.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            string name = null;

            try

            {

                if (name.Length > 0) // Exception will occur

                {

                    Console.WriteLine("Name: " + name);

                }

            }

            catch (Exception ex)

            {

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

            }

            finally

            {

                Console.WriteLine("Finally Block.");

            }

            Console.ReadLine();

        }

    }

}

If you observe the above code, we used a 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.

 

When we execute the above code, we will get the result like as shown below.

 

Exception: Object reference not set to an instance of an object.

Finally Block.

To know more in-detail about exception handling in c#, check following exception handling topics.

 

C# try-catch

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

 

To learn more about the try-catch statement, check c# try catch statement.

C# try-catch-finally

In c#, try-catch-finally is useful to handle unexpected exceptions in code. Here, finally block is useful to clean up any resources that are allocated in the try block.

 

To learn more about the try-catch-finally statement, then check c# try-catch-finally statement.

C# throw

In c#, throw keyword is useful to raise an exception manually and it will throw all the exceptions which are derived from the Exception base class.

 

To learn more about throw keyword in c#, check c# throw keyword.

 

 

PREVIOUS

C# Exception
 

NEXT

Try Catch in C#  
 

Topics Covered