Link Search Menu Expand Document

Exception Handling in C#

Exceptions are runtime errors that may cause an application to break during execution. Errors in C# can be broadly divided into types: static errors or compile-time errors, and exceptions which are also known as runtime errors. Compile-time errors in C# occur before an application starts executing. For example a missing semicolon, missing bracket, type mismatch, etc. On the other hand, runtime errors or exceptions, are not caught at compile-time and only occur when the application is running. Exceptions, if not properly dealt with can cause an application to crash.

Exception handling refers to handling a runtime error in a way that an application doesn’t crash and a readable message is conveyed to the user regarding the error. In this article, you will see how to handle exceptions in C#.

Table of Contents

  1. How Exceptions Occur
  2. How to Handle Exceptions in C#
  3. Handling All Exceptions
  4. Individually Handling Multiple Exceptions

How Exceptions Occur?

There are several reasons for an exception to occur in C#. For example, exceptions may occur if you try to access the value of an uninitialized variable, or when you try to divide a number by zero, or when you try to access an array index that doesn’t exist, etc.

Let’s see how an exception occurs in C#. In the following script, you define an array with three items. Next, you try to print the item at the 3rd index. The maximum index number for an array with 3 items is 2 since C# arrays follow zero-based indexing. Thus an exception will occur as shown in the output.

using System;

namespace DariaApp
{
class Program
{
static void Main(string[] args)
{

int[] my_arry = { 2, 3, 4 };

Console.WriteLine(my_arry[3]);

}
}
}

Output:

Exception Handling

The above exception clearly says that the “Index was outside the bounds of the array”. Or in other words, the index that you are trying to access doesn’t exist.

How to Handle Exceptions in C#

To handle an exception in C#, all you have to do is wrap the code that is likely to throw an exception inside a try block. The code that you want to execute as a result of an exception is wrapped inside a catch block that follows a try block. The following script handles the IndexOutOfRangeException that you saw previously.

using System;

namespace DariaApp
{
class Program
{
static void Main(string[] args)
{
try
{
int[] my_arry = { 2, 3, 4 };

Console.WriteLine(my_arry[3]);
}
catch
{
Console.WriteLine("The exception is caught");
}

Console.WriteLine("The application continues running after an exception ...");
}
}
}

The output shows that the exception occurred, however instead of crashing the application, the control shifted to catch block which prints a statement on the console. After handling the exception, the application execution continued.

Output:

Exception Handling C Sharp

Handling all Exceptions

You can handle all exceptions using a single catch block. You can also pass an object of the Exception class as a parameter to the catch block.  Using the Exception class object, you can print the information about the exception. For example, the following script prints the message of the exception inside the catch block.

using System;

namespace DariaApp
{
class Program
{
static void Main(string[] args)
{
try
{
int[] my_arry = { 2, 3, 4 };

Console.WriteLine(my_arry[3]);
}
catch (Exception e)
{
Console.WriteLine("The exception is caught: " + e.Message);
}

Console.WriteLine("The application continues running after an exception ...");
}
}
}

 

Output:

C Sharp Exception Handling

Individually Handling Multiple Exceptions

Instead of using a single catch block, you can use multiple catch blocks for different types of exceptions. For instance, the following script can throw the IndexOutOfRangeException as well as the DivideByZeroException. Therefore, you have two catch blocks. The first catch block handles the DivideByZeroException, while the second catch block handles the IndexOutOfRangeException. If you run the following script, you will see that the IndexOutOfRangeException exception will occur and the code in the corresponding catch block will execute.

using System;

namespace DariaApp
{
class Program
{
static void Main(string[] args)
{
try
{
int[] my_arry = { 2, 3, 4 };

Console.WriteLine(my_arry[3]);

int a = 10;
int b = 5;

int result = a / b;
Console.WriteLine(result);
}

catch (DivideByZeroException div)
{
Console.WriteLine(div.Message);
Console.WriteLine("Mention allowed array index");
}
catch (IndexOutOfRangeException ind)
{
Console.WriteLine(ind.Message);
Console.WriteLine("Mention allowed array index");
}

Console.WriteLine("The application continues running after an exception ...");
}
}
}

Output:

Exception Handling C

If you make the following modification inside the try block in the script used for the previous example, you will see that this time the script will throw the DivideByZeroException and the corresponding catch block for the DivideByZeroException will execute.

try
{
int[] my_arry = { 2, 3, 4 };

Console.WriteLine(my_arry[2]);

int a = 10;
int b = 0;

int result = a / b;
Console.WriteLine(result);
}

Output:

C Exception Handling

Other useful articles:


Back to top

© , C Sharp Online — All Rights Reserved - Terms of Use - Privacy Policy