Exception Handling in C#: Prevention and Management of Runtime Errors

Exception handling is a mechanism in C# that allows you to handle runtime errors and prevent your program from crashing. It allows you to catch errors, diagnose the problem, and take appropriate action.

An exception is an event that occurs during the execution of a program that disrupts the normal flow of the application.

To handle exceptions in C#, you use the try-catch construct. The basic syntax is as follows:

try
{
    // Code that may throw an exception
}
catch (ExceptionType ex)
{
    // Code to handle the exception
}

In the example above, the code in the try block is the code that may throw an exception. If an exception is thrown, control transfers to the catch block, where the exception is caught and processed. The ExceptionType parameter specifies the type of exception that the catch block can handle.

You can also specify a finally block, which will be executed whether an exception was thrown or not. The syntax for using a finally block is as follows:

try
{
    // Code that may throw an exception
}
catch (ExceptionType ex)
{
    // Code to handle the exception
}
finally
{
    // Code to be executed regardless of whether an exception was thrown or not
}

You can check out the list of all the ExceptionTypes in this link, but below you are going to learn about the commonly used one.

DivideByZeroException

This occurs when you try to divide a number by zero.

try
{
    int a = 10;
    int b = 0;
    int result = a / b;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero.");
}
NullReferenceException

This occurs when you try to access a member of a null object.

try
{
    string str = null;
    int length = str.Length;
}
catch (NullReferenceException ex)
{
    Console.WriteLine("Object reference not set to an instance of an object.");
}
IndexOutOfRangeException

This occurs when you try to access an index that is outside the bounds of an array.

try
{
    int[] arr = new int[5];
    int x = arr[10];
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Index was outside the bounds of the array.");
}
ArgumentException

This occurs when an argument passed to a method is invalid. This exception is typically used to indicate that an argument is null, out of range, or otherwise invalid.

try
{
    int result = Math.Sqrt(-5);
}
catch (ArgumentException ex)
{
    Console.WriteLine("ArgumentException: " + ex.Message);
}
InvalidOperationException

This occurs when a method call is invalid for the current state of an object. For example, trying to open a database connection that is already open.

Connection conn = new Connection();

try
{
    conn.Open(); //Open connection to database
    conn.Open(); //Try to reopen same connection
}
catch (InvalidOperationException ex)
{
    Console.WriteLine("InvalidOperationException: " + ex.Message);
}
28. C# - Exception

Image by rawpixel.com on Freepik


Enjoyed this post? Subscribe to my YouTube channel for more great content. Your support is much appreciated. Thank you!


Check out my Udemy profile for more great content and exclusive learning resources! Thank you for your support.
Ervis Trupja - Udemy



Enjoyed this blog post? Share it with your friends and help spread the word! Don't keep all this knowledge to yourself.