Exception Handling in C# - Textnotes

Exception Handling in C#


Exception handling is used to manage runtime errors gracefully and prevent application crashes.

1. try, catch, finally

  1. try: Contains code that may throw exceptions.
  2. catch: Handles exceptions.
  3. finally: Executes code regardless of exception occurrence (optional).

using System;

class Program
{
static void Main()
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Throws IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
Console.WriteLine("Finally block executed.");
}
}
}

Output:


Error: Index was outside the bounds of the array.
Finally block executed.

2. throw Keyword

throw is used to manually throw exceptions.


int age = -5;

if (age < 0)
{
throw new ArgumentException("Age cannot be negative");
}

Explanation:

  1. Throws an exception that can be caught by catch.

3. Creating Custom Exceptions

You can create user-defined exceptions by inheriting from Exception.


using System;

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

class Program
{
static void ValidateAge(int age)
{
if (age < 0)
throw new NegativeAgeException("Age cannot be negative");
else
Console.WriteLine("Valid age: " + age);
}

static void Main()
{
try
{
ValidateAge(-10);
}
catch (NegativeAgeException ex)
{
Console.WriteLine("Custom Exception: " + ex.Message);
}
}
}

4. Common Exception Types

Exception TypeDescription
NullReferenceExceptionObject reference is null
IndexOutOfRangeExceptionIndex exceeds array or collection bounds
DivideByZeroExceptionDivision by zero
FormatExceptionInvalid format for data conversion
OverflowExceptionValue exceeds limits of data type
InvalidOperationExceptionInvalid operation performed on object/state
ArgumentExceptionInvalid argument passed to method
FileNotFoundExceptionFile not found

Example:


string str = null;
try
{
Console.WriteLine(str.Length); // NullReferenceException
}
catch (NullReferenceException ex)
{
Console.WriteLine("Error: " + ex.Message);
}

5. Best Practices in Exception Handling

  1. Catch specific exceptions first before general exceptions.
  2. Avoid empty catch blocks; always handle or log.
  3. Use finally to release resources (files, DB connections).
  4. Throw exceptions when necessary; avoid suppressing errors.
  5. Create meaningful custom exceptions for business logic.
  6. Do not use exceptions for control flow; use them only for exceptional cases.

Example of Proper Usage:


try
{
int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
catch (FormatException ex)
{
Console.WriteLine("Invalid number format: " + ex.Message);
}
finally
{
Console.WriteLine("Execution completed.");
}

Summary of Chapter 8:

  1. try block contains risky code.
  2. catch handles specific exceptions.
  3. finally executes always.
  4. throw manually raises exceptions.
  5. Custom exceptions help define business-specific errors.
  6. Always follow best practices to write maintainable and safe code.