Exception handling in C# is a critical feature that enables a program to gracefully manage and recover from exceptional situations or errors that might occur during program execution. Exception handling provides a mechanism to intercept and manage exceptions, preventing abrupt program termination and ensuring robust error handling.
The process of exception handling in C# revolves around four key components: try block, throw statement, catch block, and finally block.
1. Try Block:
A try block is used to enclose code that might potentially throw an exception. It marks the section of code where an exception may occur. If an exception is thrown within the try block, the control is transferred to the closest matching catch block.
Syntax:
try
{
// Code that might throw an exception.
}
catch (ExceptionType1 ex)
{
// Handle ExceptionType1.
}
catch (ExceptionType2 ex)
{
// Handle ExceptionType2.
}
In this structure, the try block contains a sequence of statements that could throw exceptions. If an exception is thrown, the program's control is transferred to the closest catch block that can handle that particular exception. If no appropriate catch block is found, the program terminates abruptly.
2. Throw Statement:
The throw statement is used to explicitly throw an exception. It is typically used when an error condition or exceptional situation is encountered. When a throw statement is encountered, the program control transfers to the nearest catch block that can handle the thrown exception.
Syntax:
throw exceptionObject; // Throws an exception of a specific type.
3. Catch Block:
A catch block is used to handle a specific type of exception that can be thrown within the try block. It specifies the exception type it can catch and provides the necessary code to handle the exception.
Syntax:
catch (ExceptionType ex)
{
// Exception handling code.
}
The catch block is placed immediately after the try block and consists of the catch keyword followed by the exception type in parentheses. When an exception is thrown within the try block, the program control jumps to the catch block that matches the thrown exception's type.
4. Finally Block:
The finally block is a segment of code that is always executed after a try/catch block, regardless of whether an exception was thrown or not. This is typically used for cleaning up resources.
Syntax:
finally
{
// Code that always gets executed.
}
Here's an example that demonstrates the use of exception handling in C#:
using System;
class Program
{
static void Main()
{
try
{
int result = Divide(10, 0);
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Exception caught: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Unknown exception caught: " + ex.Message);
}
finally
{
Console.WriteLine("This code is always executed.");
}
}
static int Divide(int dividend, int divisor)
{
if (divisor == 0)
throw new DivideByZeroException("Cannot divide by zero.");
else
return dividend / divisor;
}
}
In this example, the `Divide` function attempts to perform division between `dividend` and `divisor`. If the divisor is `0`, it throws a exception with the message "DivideByZeroException".