Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Error Handling in C#

What is Error Handling?

Error handling is a critical part of programming that involves responding to and resolving errors that arise during the execution of a program. In C#, error handling helps ensure that your program can handle unexpected situations gracefully, without crashing or producing incorrect results.

Types of Errors

There are generally three types of errors in programming:

  • Syntax Errors: These occur when the code does not conform to the syntax rules of the programming language.
  • Runtime Errors: These occur during the execution of the program and are often harder to predict and catch.
  • Logical Errors: These occur when the program operates but produces incorrect results due to a flaw in the logic.

Exception Handling in C#

In C#, exception handling is used to manage runtime errors. The language provides a robust mechanism for handling these errors using the try, catch, finally, and throw keywords.

Using try and catch

The try block contains the code that may throw an exception. The catch block contains the code that handles the exception.

Example:
try {
    int[] numbers = {1, 2, 3};
    Console.WriteLine(numbers[5]);
} catch (IndexOutOfRangeException e) {
    Console.WriteLine("Index out of range: " + e.Message);
}
                    
Output:
Index out of range: Index was outside the bounds of the array.
                    

Using finally

The finally block contains code that is always executed, regardless of whether an exception was thrown or not. This is typically used for cleanup activities.

Example:
try {
    int[] numbers = {1, 2, 3};
    Console.WriteLine(numbers[5]);
} catch (IndexOutOfRangeException e) {
    Console.WriteLine("Index out of range: " + e.Message);
} finally {
    Console.WriteLine("The 'try catch' is finished.");
}
                    
Output:
Index out of range: Index was outside the bounds of the array.
The 'try catch' is finished.
                    

Throwing Exceptions

You can throw exceptions using the throw keyword. This is useful when you need to signal an error condition to the calling code.

Example:
public void CheckAge(int age) {
    if (age < 18) {
        throw new ArgumentOutOfRangeException("age", "Age must be 18 or older.");
    }
}
                    

Custom Exceptions

You can create custom exceptions by extending the Exception class. This can be useful for application-specific error handling.

Example:
public class InvalidAgeException : Exception {
    public InvalidAgeException(string message) : base(message) { }
}

public void CheckAge(int age) {
    if (age < 18) {
        throw new InvalidAgeException("Age must be 18 or older.");
    }
}