Let’s go through try-catch-finally in C# β€” essential for exception handling. Also see Common Types of Exceptions.


πŸ“Œ 1. What is Exception Handling?

  • Exceptions are runtime errors that disrupt the normal flow of a program.

  • Try-catch-finally allows you to handle errors gracefully instead of crashing the program.


πŸ“Œ 2. Basic Syntax

try
{
    // Code that might throw an exception
}
catch (ExceptionType e)
{
    // Handle the exception
}
finally
{
    // Code that always runs, whether exception occurred or not
}
  • try β†’ Wrap code that might throw an exception

  • catch β†’ Handle the exception

  • finally β†’ Optional; runs always, e.g., for cleanup


πŸ“Œ 3. Example: Simple try-catch

try
{
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[5]); // Index out of range
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Error: " + ex.Message);
}

Output:

Error: Index was outside the bounds of the array.

πŸ“Œ 4. Catching Multiple Exceptions

try
{
    int a = 10, b = 0;
    int result = a / b;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero");
}
catch (Exception ex)
{
    Console.WriteLine("Some other error: " + ex.Message);
}
  • Specific exceptions first, then general Exception

  • Avoid catching general exceptions unless necessary


πŸ“Œ 5. Finally Block

  • Executes regardless of exception occurrence

  • Useful for cleanup code (closing files, releasing resources)

try
{
    Console.WriteLine("Trying risky operation...");
}
catch (Exception ex)
{
    Console.WriteLine("Caught an exception: " + ex.Message);
}
finally
{
    Console.WriteLine("This always runs!");
}

Output:

Trying risky operation...
This always runs!

πŸ“Œ 6. Throwing Exceptions

  • You can manually throw exceptions using throw
void ValidateAge(int age)
{
    if (age < 0)
        throw new ArgumentException("Age cannot be negative");
}
 
try
{
    ValidateAge(-5);
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.Message);
}

πŸ“Œ 7. Summary Table

KeywordPurpose
tryWrap code that might fail
catchHandle specific exceptions
finallyExecute code regardless of exceptions
throwManually throw an exception

βœ… Tips:

  • Always catch specific exceptions first

  • Use finally to release resources

  • Don’t overuse empty catch blocks β€” handle or log errors properly