0
0
C Sharp (C#)programming~5 mins

Exception hierarchy in .NET in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Exceptions help your program handle errors without crashing. The exception hierarchy organizes different error types so you can catch and fix them properly.

When you want to catch specific errors like file not found or divide by zero.
When you need to create your own error types for special cases in your program.
When you want to handle all errors in a general way using a base exception.
When debugging to understand what kind of error happened.
When writing code that needs to be safe and not stop unexpectedly.
Syntax
C Sharp (C#)
try {
    // code that might cause an error
} catch (ExceptionType ex) {
    // code to handle that error
} finally {
    // code that runs no matter what
}

try block contains code that might cause an error.

catch block handles specific error types.

Examples
This catches a divide by zero error specifically.
C Sharp (C#)
try {
    int x = 5 / 0;
} catch (DivideByZeroException ex) {
    Console.WriteLine("Cannot divide by zero.");
}
This catches when you try to use an object that is null.
C Sharp (C#)
try {
    string s = null;
    Console.WriteLine(s.Length);
} catch (NullReferenceException ex) {
    Console.WriteLine("Object was null.");
}
This catches any error because Exception is the base class for all exceptions.
C Sharp (C#)
try {
    // some code
} catch (Exception ex) {
    Console.WriteLine("Some error happened.");
}
Sample Program

This program tries to access an array element that does not exist. It catches the specific error and also has a general catch. The finally block runs always.

C Sharp (C#)
using System;

class Program {
    static void Main() {
        try {
            int[] numbers = {1, 2, 3};
            Console.WriteLine(numbers[5]);
        } catch (IndexOutOfRangeException ex) {
            Console.WriteLine("Index was outside the bounds of the array.");
        } catch (Exception ex) {
            Console.WriteLine("Some other error occurred.");
        } finally {
            Console.WriteLine("This runs no matter what.");
        }
    }
}
OutputSuccess
Important Notes

All exceptions in .NET inherit from System.Exception.

You can catch specific exceptions first, then more general ones.

The finally block is useful for cleanup code that must run.

Summary

Exceptions are organized in a hierarchy starting from System.Exception.

Catching specific exceptions helps handle errors better.

Use try-catch-finally blocks to manage errors safely.