Try-Catch-Finally in C#

The try-catch-finally statement in C# provides a structured way to handle exceptions that may occur during program execution. It allows you to gracefully handle errors like division by zero, file access failures, or network timeouts without crashing your application.

Exception handling in C# is performed using three main keywords that work together to create a robust error handling mechanism.

Syntax

Following is the basic syntax of try-catch-finally statement −

try {
   // Code that may throw an exception
}
catch (ExceptionType ex) {
   // Handle the exception
}
finally {
   // Code that always executes
}

You can also use multiple catch blocks for different exception types −

try {
   // Code that may throw an exception
}
catch (SpecificException ex) {
   // Handle specific exception
}
catch (Exception ex) {
   // Handle any other exception
}
finally {
   // Cleanup code
}

Keywords Explanation

  • try − Contains code that might throw an exception. If an exception occurs, control immediately transfers to the appropriate catch block.

  • catch − Handles specific exceptions thrown by the try block. You can have multiple catch blocks for different exception types.

  • finally − Contains code that always executes, regardless of whether an exception occurred. Used for cleanup operations like closing files or database connections.

Try-Catch-Finally Flow TRY Execute code CATCH Handle exception SUCCESS No exception FINALLY Always executes Exception Success Finally block runs regardless of exception occurrence

Using Try-Catch-Finally for Division

Example

using System;

class DivNumbers {
   int result;

   DivNumbers() {
      result = 0;
   }

   public void division(int num1, int num2) {
      try {
         result = num1 / num2;
         Console.WriteLine("Division successful!");
      } catch (DivideByZeroException e) {
         Console.WriteLine("Exception caught: {0}", e.Message);
      } finally {
         Console.WriteLine("Result: {0}", result);
         Console.WriteLine("Finally block executed");
      }
   }

   static void Main(string[] args) {
      DivNumbers d = new DivNumbers();
      Console.WriteLine("Test 1: Division by zero");
      d.division(25, 0);
      
      Console.WriteLine("\nTest 2: Normal division");
      d.division(25, 5);
   }
}

The output of the above code is −

Test 1: Division by zero
Exception caught: Attempted to divide by zero.
Result: 0
Finally block executed

Test 2: Normal division
Division successful!
Result: 5
Finally block executed

Using Multiple Catch Blocks

Example

using System;

class MultipleExceptions {
   public static void TestExceptions(int[] numbers, int index, int divisor) {
      try {
         int result = numbers[index] / divisor;
         Console.WriteLine("Result: {0}", result);
      } catch (IndexOutOfRangeException ex) {
         Console.WriteLine("Index Error: {0}", ex.Message);
      } catch (DivideByZeroException ex) {
         Console.WriteLine("Division Error: {0}", ex.Message);
      } catch (Exception ex) {
         Console.WriteLine("General Error: {0}", ex.Message);
      } finally {
         Console.WriteLine("Cleanup completed");
      }
   }

   static void Main(string[] args) {
      int[] arr = {10, 20, 30};
      
      Console.WriteLine("Test 1: Valid operation");
      TestExceptions(arr, 1, 2);
      
      Console.WriteLine("\nTest 2: Index out of range");
      TestExceptions(arr, 5, 2);
      
      Console.WriteLine("\nTest 3: Division by zero");
      TestExceptions(arr, 1, 0);
   }
}

The output of the above code is −

Test 1: Valid operation
Result: 10
Cleanup completed

Test 2: Index out of range
Index Error: Index was outside the bounds of the array.
Cleanup completed

Test 3: Division by zero
Division Error: Attempted to divide by zero.
Cleanup completed

Try-Finally Without Catch

You can use try-finally without catch blocks when you need cleanup code but don't want to handle exceptions locally −

Example

using System;

class ResourceManagement {
   public static void ProcessFile() {
      Console.WriteLine("Opening file resource...");
      try {
         Console.WriteLine("Processing file...");
         throw new InvalidOperationException("File processing failed");
      } finally {
         Console.WriteLine("Closing file resource...");
         Console.WriteLine("Resource cleanup completed");
      }
   }

   static void Main(string[] args) {
      try {
         ProcessFile();
      } catch (Exception ex) {
         Console.WriteLine("Caught in Main: {0}", ex.Message);
      }
   }
}

The output of the above code is −

Opening file resource...
Processing file...
Closing file resource...
Resource cleanup completed
Caught in Main: File processing failed

Best Practices

Practice Description
Catch specific exceptions first Place more specific exception types before general ones
Use finally for cleanup Always close resources like files, connections in finally block
Don't catch and ignore Always log or handle exceptions appropriately
Keep try blocks minimal Only include code that might throw exceptions in try blocks

Conclusion

The try-catch-finally statement provides structured exception handling in C#. The try block contains potentially risky code, catch blocks handle specific exceptions, and the finally block ensures cleanup code always runs. This pattern helps create robust applications that handle errors gracefully.

Updated on: 2026-03-17T07:04:35+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements