Try/catch/finally/throw keywords in C#

Exception handling in C# is implemented using four key keywords that work together to manage runtime errors gracefully. The try block contains code that might throw an exception, catch blocks handle specific exceptions, finally executes cleanup code regardless of whether an exception occurs, and throw is used to raise exceptions manually.

Syntax

Following is the basic syntax for exception handling in C# −

try {
   // code that might throw an exception
}
catch (SpecificExceptionType ex) {
   // handle specific exception
}
catch (Exception ex) {
   // handle any remaining exceptions
}
finally {
   // cleanup code (always executes)
}

To throw an exception manually −

throw new ExceptionType("Error message");

Exception Handling Keywords

  • try − Defines a block of code to monitor for exceptions. Must be followed by at least one catch or finally block.

  • catch − Handles specific exceptions thrown in the try block. Multiple catch blocks can handle different exception types.

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

  • throw − Manually raises an exception when a specific condition is met or to re-throw a caught exception.

Using Try-Catch-Finally

Example

using System;

class Program {
   public static void Main() {
      int[] numbers = {1, 2, 3};
      
      try {
         Console.WriteLine("Accessing valid index: " + numbers[1]);
         Console.WriteLine("Accessing invalid index: " + numbers[5]);
      }
      catch (IndexOutOfRangeException ex) {
         Console.WriteLine("Index error: " + ex.Message);
      }
      catch (Exception ex) {
         Console.WriteLine("General error: " + ex.Message);
      }
      finally {
         Console.WriteLine("Finally block always executes");
      }
      
      Console.WriteLine("Program continues after exception handling");
   }
}

The output of the above code is −

Accessing valid index: 2
Index error: Index was outside the bounds of the array.
Finally block always executes
Program continues after exception handling

Using Throw to Raise Exceptions

Example

using System;

class AgeValidator {
   public static void ValidateAge(int age) {
      if (age  150) {
         throw new ArgumentException("Age cannot be greater than 150");
      }
      Console.WriteLine("Valid age: " + age);
   }
}

class Program {
   public static void Main() {
      try {
         AgeValidator.ValidateAge(25);
         AgeValidator.ValidateAge(-5);
      }
      catch (ArgumentException ex) {
         Console.WriteLine("Validation error: " + ex.Message);
      }
      
      try {
         AgeValidator.ValidateAge(200);
      }
      catch (ArgumentException ex) {
         Console.WriteLine("Validation error: " + ex.Message);
      }
   }
}

The output of the above code is −

Valid age: 25
Validation error: Age cannot be negative
Validation error: Age cannot be greater than 150

Multiple Catch Blocks

Example

using System;

class Calculator {
   public static void Main() {
      try {
         string input = "abc";
         int number = int.Parse(input);
         int result = 10 / number;
         Console.WriteLine("Result: " + result);
      }
      catch (FormatException ex) {
         Console.WriteLine("Format error: Cannot convert string to number");
      }
      catch (DivideByZeroException ex) {
         Console.WriteLine("Math error: Cannot divide by zero");
      }
      catch (Exception ex) {
         Console.WriteLine("Unexpected error: " + ex.Message);
      }
      finally {
         Console.WriteLine("Calculation attempt completed");
      }
   }
}

The output of the above code is −

Format error: Cannot convert string to number
Calculation attempt completed

Conclusion

The try-catch-finally-throw keywords in C# provide a robust mechanism for handling exceptions. The try block monitors code for exceptions, catch blocks handle specific errors, finally ensures cleanup code runs regardless of exceptions, and throw allows manual exception raising for custom error conditions.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements