C sharp - Exception in C#

Definition:
An exception in C# is an error that occurs during program execution (runtime) that disrupts the normal flow of the application.

When an exception occurs, C# creates an exception object and passes it to the runtime system to handle it. If not handled, the program will crash.

 Common Causes of Exceptions:

  • Dividing by zero

  • Accessing an invalid array index

  • Opening a file that doesn’t exist

  • Invalid type conversions

 Exception Handling Keywords in C#:

Keyword Description
try Block where you write code that may cause an exception
catch Block that handles the exception
finally Block that always executes (used for cleanup)
throw Used to manually throw an exception

 Example:

try {
    int a = 10;
    int b = 0;
    int result = a / b; // Causes DivideByZeroException
}
catch (DivideByZeroException e) {
    Console.WriteLine("Error: " + e.Message);
}
finally {
    Console.WriteLine("This block always runs.");
}

 Benefits of Exception Handling:

  • Prevents application crashes

  • Makes debugging easier

  • Allows custom error messages and recovery

  • Keeps code clean and readable