Introduction to Exceptions in C# Programming


Exceptions in C# are mechanisms for handling errors or unexpected situations that occur during program execution. Proper exception handling ensures that your program behaves predictably even when errors occur.

What is an Exception?

An exception is an object that represents an error or unexpected behavior. When an exception occurs, it disrupts the normal flow of the program.

Common Exception Types in C#

  • System.Exception: The base class for all exceptions.
  • System.NullReferenceException: Occurs when attempting to access an object that is null.
  • System.IndexOutOfRangeException: Happens when accessing an index that is outside the bounds of an array.
  • System.DivideByZeroException: Raised when dividing a number by zero.
  • System.InvalidOperationException: Thrown when a method call is invalid in the current state.

Basic Exception Handling

In C#, exceptions are handled using try, catch, and optionally finally blocks. Here's the syntax:

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

Step-by-Step Example

Example 1: Handling Division by Zero

In this example, we will handle a DivideByZeroException.

    using System;
   class Program {
        static void Main() {
            try {
                int numerator = 10;
                int denominator = 0;
                int result = numerator / denominator;
                Console.WriteLine("Result: " + result);
            } catch (DivideByZeroException e) {
                Console.WriteLine("Error: " + e.Message);
            }
        }
    }
        

Output:

Error: Attempted to divide by zero.

Example 2: Handling Null Reference

In this example, we handle a NullReferenceException.

    using System;
   class Program {
        static void Main() {
            try {
                string str = null;
                Console.WriteLine(str.Length);
            } catch (NullReferenceException e) {
                Console.WriteLine("Error: " + e.Message);
            }
        }
    }
        

Output:

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

Using Multiple Catch Blocks

You can use multiple catch blocks to handle different types of exceptions.

    using System;
   class Program {
        static void Main() {
            try {
                int[] numbers = { 1, 2, 3 };
                Console.WriteLine(numbers[5]);
            } catch (IndexOutOfRangeException e) {
                Console.WriteLine("Index error: " + e.Message);
            } catch (Exception e) {
                Console.WriteLine("General error: " + e.Message);
            }
        }
    }
        

Output:

Index error: Index was outside the bounds of the array.

Conclusion

Exception handling is a crucial part of robust and reliable C# programming. It ensures your application can gracefully handle unexpected scenarios, providing a better user experience and reducing application crashes.




Advertisement