In C#, an exception is an unexpected or abnormal condition that occurs during the execution of a program that disrupts the normal flow of the program's instructions. When an exception occurs, the runtime environment generates an object of a specific type (derived from the Exception
class) to represent the exception, and the program can handle the exception using exception handling mechanisms.
Here's a simple explanation with an example:
Suppose we have a program that reads a number from the user and divides it by another number. However, if the user enters zero as the divisor, it will result in a division by zero exception.
Example
using System;
class Program
{
static void Main(string[] args)
{
try
{
Console.Write("Enter a number: ");
int number1 = int.Parse(Console.ReadLine());
Console.Write("Enter another number: ");
int number2 = int.Parse(Console.ReadLine());
int result = DivideNumbers(number1, number2);
Console.WriteLine("Result of division: " + result);
}
catch (FormatException)
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
catch (DivideByZeroException)
{
Console.WriteLine("Error: Division by zero is not allowed.");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
static int DivideNumbers(int dividend, int divisor)
{
return dividend / divisor;
}
}
In this example:
try-catch
block to handle exceptions that may occur during the execution of the code inside the try
block.try
block, we prompt the user to enter two numbers and attempt to divide the first number by the second number.FormatException
will be thrown, and we catch it to inform the user about the invalid input.DivideByZeroException
will be thrown, and we catch it to handle the division by zero error.catch
block to catch any other exceptions that may occur and display a generic error message.Exception handling allows the program to gracefully handle unexpected errors and prevent the program from crashing. It provides a way to recover from errors, log diagnostic information, and guide users on how to resolve the issue.