Exception handling is a way to gracefully handle runtime errors in a C# program. When an error occurs during the execution of a program, an exception is thrown, which can be caught and handled in a try-catch block. Here's an example:
try
{
// Code that may throw an exception
int x = 10 / 0; // This will throw a divide by zero exception
}
catch (DivideByZeroException ex)
{
// Handle the exception
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
// Code that will always execute, regardless of whether an exception was thrown or not
Console.WriteLine("The program has finished executing.");
}
In this example, we have a try-catch-finally block. The code inside the try block attempts to divide the number 10 by zero, which is an illegal operation and will throw a DivideByZeroException.
When the exception is thrown, the catch block catches it and executes its code. In this case, we simply print an error message that includes the exception message.
The finally block is optional and will always execute, regardless of whether an exception was thrown or not. In this example, we print a message that indicates the program has finished executing.
There are other types of exceptions that can be caught, such as ArgumentException, ArgumentNullException, IndexOutOfRangeException, and so on. It's important to catch only the specific exceptions that you expect might be thrown and to handle them appropriately.
In addition to try-catch-finally blocks, C# also provides the throw statement, which allows you to manually throw an exception. This can be useful when you want to create a custom exception that isn't already provided by the .NET Framework.
if (x < 0)
{
throw new ArgumentException("x must be a positive integer.");
}
In this example, we use the throw statement to manually throw an ArgumentException if the variable x is less than zero. We pass a string message to the constructor of the ArgumentException, which will be displayed when the exception is caught and handled.