CodeToLive

Exception Handling

Exception handling allows you to handle runtime errors gracefully using try, catch, and finally blocks.

Try-Catch Example


try
{
    int result = 10 / 0; // Division by zero
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Error: " + ex.Message);
}
finally
{
    Console.WriteLine("This block always executes.");
}
      

Custom Exceptions


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

throw new CustomException("This is a custom exception.");
      
Next: File Handling