C# Exception Handling
Objectives
- What is Exception Handling ?
- Try-catch blocks
- Handling exceptions
- Throwing exceptions
What is Exception Handling?
The Exception Handling are mechanism in programming that allows you to handle errors or exceptional conditions that occur during the execution of a program.
Exception handling provides a structured way to detect, handle, and recover from errors, preventing the program from crashing unexpectedly.
Try-Catch Blocks:
Try-Catch Blocks are used to handle exceptions.
The try block contains the code that may throw an exception.
The catch block catches and handles the exception if one occurs.
try
{
// Code that may throw an exception
}
catch (Exception ex)
{
// Code to handle the exception
}
Handling Exceptions:
The catch block, it can specify the type of exception you want to catch using the catch clause followed by the exception type.
You can have multiple catch blocks to handle different types of exceptions or handle them differently based on their type.
try
{
int x = 10;
int y = 0;
int result = x / y; // This will throw a DivideByZeroException
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: Division by zero.");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
Throwing Exceptions:
The Throwing Exceptions is the process of explicitly raising an exception to indicate that an error condition has occurred.
throw exceptions using the throw keyword followed by an exception object or a new instance of an exception class.
try
{
throw new InvalidOperationException("Invalid operation");
}
catch (InvalidOperationException ex)
{
Console.WriteLine("Error: " + ex.Message);
}