Skip to content

Exception Handling

Sann Lynn Htun edited this page Nov 19, 2024 · 1 revision

C# Exception Handling

Exception handling in C# is a mechanism to handle runtime errors, ensuring the program can respond to unexpected conditions gracefully. The primary way to handle exceptions is through the use of try, catch, finally, and throw statements.

Key Concepts

  1. try-catch Block

Surround code that might throw an exception with a try block, and handle exceptions with one or more catch blocks.

Examples

Basic try-catch Example

using System;

class Program
{
    static void Main()
    {
        try
        {
            int[] numbers = { 1, 2, 3 };
            Console.WriteLine(numbers[5]); // This will throw an exception
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Advanced Features

  1. finally Block

The finally block contains code that is always executed, regardless of whether an exception is thrown or caught. It is typically used for cleanup code.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        StreamReader reader = null;
        try
        {
            reader = new StreamReader("example.txt");
            Console.WriteLine(reader.ReadToEnd());
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
        finally
        {
            if (reader != null)
            {
                reader.Close();
            }
            Console.WriteLine("Cleanup code executed.");
        }
    }
}
  1. throw Statement

Use the throw statement to explicitly throw an exception, either caught or newly created.

using System;

class Program
{
    static void Main()
    {
        try
        {
            ValidateAge(15);
        }
        catch (ArgumentOutOfRangeException ex)
        {
            Console.WriteLine($"Exception caught: {ex.Message}");
        }
    }

    static void ValidateAge(int age)
    {
        if (age < 18)
        {
            throw new ArgumentOutOfRangeException("Age must be 18 or older.");
        }
    }
}
  1. Custom Exceptions

Define your own exceptions by creating a class that inherits from Exception.

using System;

class Program
{
    static void Main()
    {
        try
        {
            PerformOperation(0);
        }
        catch (CustomException ex)
        {
            Console.WriteLine($"Custom exception caught: {ex.Message}");
        }
    }

    static void PerformOperation(int value)
    {
        if (value == 0)
        {
            throw new CustomException("Value cannot be zero.");
        }
    }
}

public class CustomException : Exception
{
    public CustomException(string message) : base(message) { }
}

Summary

  • try-catch: Handle exceptions where they occur.
  • finally: Execute code regardless of exceptions, useful for cleanup.
  • throw: Explicitly throw exceptions.
  • Custom Exceptions: Create exceptions specific to application needs.

C# exception handling provides robust mechanisms to manage errors and maintain program stability, making it easier to develop reliable applications.

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally