Mark As Completed Discussion

Catching and Handling Exceptions

When writing .NET applications, it is important to anticipate and handle potential exceptions that may occur during runtime. Exceptions are a way of throwing and propagating errors or exceptional conditions that interrupt the normal flow of your code.

In C#, exceptions are represented by classes that inherit from the Exception base class. The .NET Framework provides many built-in exception classes for common scenarios, such as DivideByZeroException when dividing a number by zero.

To catch and handle exceptions, you can use the try-catch statement. The code inside the try block is monitored for any exceptions. If an exception occurs, it is caught by the corresponding catch block. You can have multiple catch blocks to handle different types of exceptions.

Here is an example of catching and handling exceptions:

TEXT/X-CSHARP
1try
2{
3    // Code that may throw an exception
4    int result = Divide(10, 0);
5    Console.WriteLine(result);
6}
7catch (DivideByZeroException ex)
8{
9    // Handling the DivideByZeroException
10    Console.WriteLine("Cannot divide by zero");
11}
12catch (Exception ex)
13{
14    // Handling any other exception
15    Console.WriteLine(ex.Message);
16}

In this example, we try to divide a number by zero using the Divide method. If a DivideByZeroException occurs, we catch it and display a custom message. If any other exception occurs, we catch it using the Exception base class and display the exception message.

By catching and handling exceptions, you can handle errors gracefully and provide meaningful feedback to the user or log the error for debugging purposes.

C#
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment