Exception handling is a technique used in programming to handle errors and unexpected situations that may occur during program execution. In C#, exception handling is done using try-catch-finally blocks.
The try block contains the code that may generate an exception, and the catch block contains the code that is executed if an exception is thrown. The finally block is executed regardless of whether an exception is thrown or not, and is used for cleanup operations like closing files, releasing resources, etc.
Here’s an example of how to use try-catch-finally blocks in C#:
using System;
class Program
{
static void Main(string[] args)
{
try
{
int x = 10;
int y = 0;
int result = x / y;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException e)
{
Console.WriteLine("Error: Cannot divide by zero.");
}
finally
{
Console.WriteLine("Finally block executed.");
}
}
}
In this example, we are trying to divide the integer variable “x” by zero, which will generate a DivideByZeroException. We have enclosed this code in a try block and catch the DivideByZeroException in the catch block. In this block, we display an error message indicating that we cannot divide by zero.
In the finally block, we have written a message indicating that the finally block has executed. Finally blocks are often used to release resources, such as closing a file or database connection, regardless of whether an exception was thrown.
When you run this program, it will catch the DivideByZeroException and display an error message. It will then execute the finally block, displaying a message indicating that it has been executed.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.