Try Catch in C#

In c#, the try-catch statement is useful to handle unexpected or runtime exceptions that will occur during the program's execution. The try-catch statement will contain a try block followed by one or more catch blocks to handle different exceptions.

 

In c#, whenever an exception occurred in the try block, the CLR (common language runtime) will look for the catch block that handles an exception. If the 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 program's execution.

C# try-catch Syntax

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

 

try
{
   // code that may cause exception
}
catch (Exception ex)
{
   // exception handling
}

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 move to catch block to handle those exceptions.

 

In a try-catch statement, the catch block will execute only when an exception occurred in the code that is guarded by try block.

C# try-catch Example

Following is the example of using a try-catch statement in c# to handle the exceptions.

 

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);
          }
          Console.ReadLine();
       }
    }
}

If you observe the above code, we used try and catch blocks to handle runtime or unexpected errors during the 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.

 

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

 

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

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

 

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

C# try with Multiple catch Blocks

In the above try-catch statement example, we used only single catch block with the Exception base class argument to handle all the exceptions.

 

If we want to handle a different type of exceptions in different ways, then we can specify multiple catch blocks with different exception types in the same try-catch statement, and this process is called exception filtering.

 

If we define multiple catch blocks with a try statement, then the first catch statement that can handle an exception will be executed, any following catch statements that are even more compatible to handle an exception will be ignored, so the order of catch blocks must be always from most specific to least specific.

 

Following is the example of defining multiple catch blocks in a try-catch statement to handle different exceptions in different ways.

 

using System;

namespace TutlaneExamples
{
    class Program
    {
       static void Main(string[] args)
       {
          try
          {
             Console.WriteLine("Enter x value:");
             int x = int.Parse(Console.ReadLine());
             Console.WriteLine("Enter y value:");
             int y = int.Parse(Console.ReadLine());
             Console.WriteLine(x / y);
          }
          catch (FormatException ex)
          {
             Console.WriteLine("Input string was not in a correct format.");
          }
          catch (InvalidOperationException ex)
          {
               Console.WriteLine("Not a valid numbers to perform operation");
          }
          catch (DivideByZeroException ex)
          {
             Console.WriteLine("Cannot Divide By Zero");
          }
          Console.ReadLine();
       }
    }
}

If you observe the above example, we defined multiple catch blocks to handle different exception types to easily get know what exact error it is and fix it easily.

 

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

 

Enter x value:
10
Enter y value:
0
Cannot Divide By Zero

This is how we can use multiple catch blocks with a single try block to handle different types of exceptions based on our requirements.

C# Invalid Catch Blocks

In c#, defining a parameterless catch block (catch{}) and catch block with an exception argument (catch (Exception ex) { }) are not allowed in the same try-catch statement because both will do the same thing.

 

Following is the example of defining an invalid catch blocks in the same try-catch statement.

 

try
{
// code that may cause an exception
}
catch{
// Exception Handling
}
catch (Exception ex) {
// Exception Handling
}

If we use a parameterless catch block (catch{}) or catch block with an exception argument (catch (Exception ex) {}) with other catch blocks, then those parameters must be last. Otherwise, we will get a compile-time error.

 

Following is the invalid way of defining a multiple catch blocks with a parameterless catch block in the same try-catch statement.

 

try
{
// code that may cause an exception
}
catch {
// Exception Handling
}
catch (FormatException ex)
{
// Exception Handling
}
catch (InvalidOperationException ex)
{
// Exception Handling
}

Following are the few point which we need to consider while defining multiple catch blocks.

 

  • Multiple catch blocks with the same exception type are not allowed.
  • Defining a parameterless catch block (catch{}) and catch block with an exception argument (catch (Exception ex) { }) are not allowed in the same try-catch statement because both will do the same thing.
  • While defining multiple catch blocks, the order of catch blocks must be always from most specific to least specific.
  • A parameterless catch block (catch{}) or catch block with an exception argument (catch (Exception ex) {}) must be the last block if we use it with other catch blocks; otherwise, we will get a compile-time error.

C# Nested try-catch Statements

In c#, we can define a try-catch statement within another try-catch statement based on our requirements. In nested try-catch statements, if there isn’t any inner catch block with an appropriate exception type; then the exception will flow to the outer catch block.

 

Following is the example of defining nested try-catch statements in c#.

 

using System;

namespace TutlaneExamples
{
    class Program
    {
       static void Main(string[] args)
       {
          try
          {
             try
             {
                Console.WriteLine("Enter x value:");
                int x = int.Parse(Console.ReadLine());
                Console.WriteLine("Enter y value:");
                int y = int.Parse(Console.ReadLine());
                Console.WriteLine(x / y);
             }
             catch (FormatException ex)
             {
                Console.WriteLine("Input string was not in a correct format.");
             }
          }
          catch (Exception ex)
          {
             Console.WriteLine("Exception: " + ex.Message);
          }
          Console.ReadLine();
       }
    }
}

If you observe the above example, we defined a try-catch statement within another try-catch statement. Here, if we get any exception other than FormatException in an inner try-catch statement, then the exception will flow to outer catch block until it finds an appropriate exception filter.

 

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

 

Enter x value:
10
Enter y value:
0
Exception: Attempted to divide by zero.

If you observe the above result, the inner try-catch statement has failed to handle the exception, so the catch block in the outer try-catch statement has been handled the exception.

C# try-catch Overview

The following are the important points that you need to remember about the try-catch statement.

 

  • In try-catch statement, the try block will hold the code that may raise an exception, and in the catch block, exception handling can be done.
  • The try-catch statement will contain a try block followed by one or more catch blocks to handle different exceptions.
  • In c#, whenever an exception occurred in the try block, then the CLR (common language runtime) will look for the appropriate catch block that handles an exception.
  • In c#, we can use nested try-catch statements.
  • In nested try-catch statements, if there isn’t any inner catch block with an appropriate exception type; then the exception will be caught by an outer catch block.