Exception Handling in C#

Exception Handling in C# with Examples

In this article, I will discuss Exception Handling in C# with Examples. This is one of the most important concepts in C#. As a developer, handling an exception is your key responsibility while developing an application. Exception Handling is a procedure for handling an exception that occurs during the execution of a program. As part of this article, we will discuss the following pointers in detail.

  1. What are the Different Types of Errors?
  2. What is an Exception in C#?
  3. Who is responsible for the abnormal termination of the program whenever runtime errors occur in the program?
  4. What happens if an Exception is Raised in the program?
  5. What does CLR do when an Exception Occurs in the Program?
  6. What is Exception Handling in C#?
  7. Why do we need Exception Handling in C#?
  8. What is the Procedure to Handle Exceptions in C#?
  9. What is the Logical Implementation in C# to Handle Exception?
  10. Exception handling in C# using Try Catch implementation
  11. Properties of Exception Class in C#
Types of Errors in C#

When we write and execute our code in the .NET framework, two types of error occurrences are possible. They are as follows:

  1. Compilation Errors
  2. Runtime Errors
Compilation Error in C#

The error that occurs in a program during compilation is known as a compilation error (compile-time error). These errors occur due to syntactical mistakes in the program. These errors occur by typing the wrong syntax, like missing double quotes in a string value and missing terminators in a statement, typing wrong spelling for keywords, assigning wrong data to a variable, trying to create an object for abstract class and interface, etc. So, whenever we compile the program, the compiler recognizes these errors and shows us the list of errors.

In simple words, this type of error occurs due to a poor understanding of the programming language. The compiler identifies these errors, which can be rectified before the program is executed. Thus, these errors do not harm the program’s execution.

Runtime Error in C#

The errors that occur at the time of program execution are called runtime errors. These errors occur at runtime due to various reasons, such as when we are entering the wrong data into a variable, trying to open a file for which there is no permission, trying to connect to the database with the wrong user ID and password, the wrong implementation of logic, and missing required resources, etc. So, in simple words, we can say that the errors that come while running the program are called runtime errors.

Runtime errors are dangerous because whenever they occur in the program, the program terminates abnormally on the same line where the error occurred without executing the next line of code.

Note: The compiler will never check the logic; it will only check the syntaxes. So, the compiler will identify the syntax error but not the logical error. 

Are Runtime Errors Dangerous?

Yes, runtime errors are dangerous. If you are transferring money, there are two updated statements. One update statement will deduct the money from the source account, and another update statement will add the money to the destination account. Suppose the first update statement was executed successfully, and before executing the second update statement, some runtime error occurred. That means the money is deducted from your account but not added to the destination account.

Then what will you do? You might be contacted by the bank, or you might go to the nearest bank and investigate what happens. Why is the money deducted from my account, and why is it not added to the destination account? This is the problem, and it is very dangerous, and it is because we are not handling the runtime errors in our application.

What is an Exception in C#?

An Exception is a class in C# that is responsible for abnormal program termination when runtime errors occur while running the program. These errors (runtime) are very dangerous because whenever they occur, the program terminates abnormally on the same line where the error occurs without executing the next line of code.

Note: Most people say Runtime Errors are Exceptions, which is not true. Exceptions are classes that are responsible for the abnormal termination of the program when runtime errors occur.

Who is Responsible for the Abnormal Termination of the Program whenever Runtime Errors occur?

Objects of Exception classes are responsible for abnormal termination of the program whenever runtime errors occur. These exception classes are predefined under BCL (Base Class Libraries), where a separate class is provided for every different type of exception, like

  1. IndexOutOfRangeException
  2. FormatException
  3. NullReferenceException
  4. DivideByZeroException
  5. FileNotFoundException
  6. SQLException,
  7. OverFlowException, etc.

Each exception class provides a specific exception error message. All the above exception classes are responsible for abnormal program termination and will display an error message that specifies the reason for abnormal termination, i.e., they provide an error message specific to that error.

So, whenever a runtime error occurs in a program, first, the Exception Manager under the CLR (Common Language Runtime) identifies the type of error that occurs in the program. Then, the Exception Manager creates an object of the Exception class related to that error and throws that object, which will immediately terminate the program abnormally on the line where the error occurred and display the error message related to that class.

Note: Exception class is the superclass of all Exception classes in C#.

What happens if an Exception is Raised in the Program in C#?

When an Exception is raised in C#, the program execution is terminated abnormally. That means the statements placed after the exception-causing statements are not executed, but the statements placed before that exception-causing statement are executed by CLR.

What does CLR do when an Exception Occurs in the program?

The CLR creates the exception class object that is associated with that logical mistake (exception) and terminates the program execution by throwing that exception object by using the throw keyword. So, we can say an exception is an event that occurs during the execution of a program that disrupts the normal flow of instruction execution. Let’s understand this with an example.

Program Execution without Exception in C#

The following C# example shows program execution without exception. This is a very simple program; we divide the numbers by two and print the result on the console.

using System;
namespace ExceptionHandlingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 20;
            int b = 10;
            int c;
            Console.WriteLine("A VALUE = " + a);
            Console.WriteLine("B VALUE = " + b);
            c = a / b;
            Console.WriteLine("C VALUE = " + c);
            Console.ReadKey();
        }
    }
}
Output:

What CLR does when an exception occurred in the program?

Program Execution with Exception in C#

The following example shows program execution with an exception. As you can see in the code below, we are dividing an integer number by 0, which is impossible in mathematics. So, it will throw the Divide By Zero Exception in this case. The statements present before the exception-causing statement, i.e., before c = a / b, are executed, and the statements present after the exception-causing statement will not be executed.

using System;
namespace ExceptionHandlingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 20;
            int b = 0;
            int c;
            Console.WriteLine("A VALUE = " + a);
            Console.WriteLine("B VALUE = " + b);
            c = a / b;
            Console.WriteLine("C VALUE = " + c);
            Console.ReadKey();
        }
    }
}
Output:

Who is responsible for abnormal termination of the program whenever runtime errors occur in the program?

After printing the above value, we will get the error below.

Program Execution with Exception in C#

Explanation:

The CLR terminates the program execution by throwing DivideByZeroException because the logical mistake we committed here is dividing an integer number by integer zero. As we know, dividing an integer number by zero is impossible. So, what CLR will do in this case, first it will check what type of logical error is this. It will find that it will be a Divide By Zero Logical Error. So, then what CLR will do is it will create an instance of the DivideByZeroException class, and then it will throw that instance by using the throw statement like throw new DivideByZeroException(); From the above program, we can define the exception technically as follows:

  1. An exception is an event because when an exception is raised, the CLR internally executes some logic to prepare exception-related messages.
  2. Exceptions are signals because, by looking into the exception message, developers will take necessary actions against that exception.
Is the above Exception Message User Understandable?

The answer is no. The user cannot understand the above exception message because it is a NET-based exception message. So, the user cannot make any decision alone to resolve the above problem. A developer should guide the user to solve the above problem.

What is the Solution to the Above problem?

The developer’s responsible for converting .NET exception messages into user-understandable message formats. To solve this problem, the developer should handle the exception. Using the exception handling mechanism, the developer can catch the exception and print and display user-understandable messages.

What is Exception Handling in C#?

The process of catching the exception for converting the CLR-given exception message to an understandable end-user message and stopping the abnormal termination of the program whenever runtime errors occur is called Exception Handling in C#. Once we handle an exception under a program, we will get the following advantages:

  1. We can stop the Abnormal Termination
  2. We can perform any corrective action that may resolve the problem.
  3. Displaying a user-friendly error message so that the user can resolve the problem provided if it is under his control.
Why do we need Exception Handling in C#?

We need exception handling in C# for two reasons.

  1. To stop the Abnormal Termination of the program
  2. To provide users with understandable messages when an exception is raised. So that users can make their own decisions without the developer’s help.

Basically, by implementing Exception handling, we are giving a program the ability to talk to the user on behalf of a developer.

What is the Procedure to Handle Exceptions in C#?

The Exception Handling in C# is a four steps procedure

  1. Preparing the exception object that is appropriate to the current logical mistake.
  2. Throwing that exception to the appropriate exception handler.
  3. Catching that exception
  4. Taking necessary actions against that exception
How can we handle an Exception in .NET?

There are two methods to handle the exception in .NET

  1. Logical Implementation
  2. Try Catch Implementation

What is the Logical Implementation in C# to Handle Exception?

In a logical implementation, we need to handle exceptions using logical statements. In real-time programming, the first and foremost importance is always given to logical implementation only. If it is impossible to handle an exception using logical implementation, then we need to go for try-catch implementation.

Handling Exceptions in C# using Logical Implementation

The following example shows how to handle exceptions in C# using logical Implementation. Here, we are checking the second number, i.e., the variable Number2 value. If it equals 0, then we are printing one message saying the second number should not be zero. Otherwise, if the second number is not zero, then we are performing our division operation and showing the results on the console. Here, we are using an IF-ELSE logical statement to handle the exception.

using System;
namespace ExceptionHandlingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int Number1, Number2, Result;
            Console.WriteLine("Enter First Number:");
            Number1 = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Second Number:");
            Number2 = int.Parse(Console.ReadLine());
            if (Number2 == 0)
            {
                Console.WriteLine("Second Number Should Not Be Zero");
            }
            else
            {
                Result = Number1 / Number2;
                Console.WriteLine($"Result = {Result}");
            }
            Console.ReadKey();
        }
    }
}
Output:

Handling Exceptions in C# using Logical Implementation

In the above case, when the user enters the second number, a zero exception will be raised, and that is handled using the logical implementation in C#. But while we are entering two numbers, if we enter any character instead of a number, then it will give you one exception, which is FormatException, which is not handled in this program, as shown below.

Handling Exceptions using Logical Implementation

Here we entered the second value as “abc”. So, it will give us the below exception.

What is the procedure to Handle Exception in C#.

To handle such types of exceptions in C#, we need to implement a try-catch. The point that you need to remember is that if we are unable to handle the exception using logical implementation, we need to implement a try-catch.

Exception handling in C# using Try Catch implementation

The .NET framework provides three keywords to implement the try-catch implementation. They are as follows:

  1. Try
  2. Catch
  3. finally
Try Block:

The try keyword establishes a block in which we need to write the exception causing and its related statements. That means exception-causing statements and the related statements, which we should not execute when an exception occurs, must be placed in the try block. When the exception occurs, the CLR will create an instance of the Exception class based on the logical error and then throw that Exception object, which the corresponding catch block will handle.

Catch Block:

The catch block is used to catch the exception that is thrown from its corresponding try block. It has the logic to take necessary actions on that caught exception. The Catch block syntax in C# looks like a constructor. It does not take accessibility modifiers, normal modifiers, or return types. It takes only a single parameter of type Exception or any child class of the parent Exception class. Inside the catch block, we can write any statement that is legal in .NET, including raising an exception. In this case, we can stop the abnormal termination of the program, and we can also give the user an understandable error message so that the user can take necessary action to resolve the error.

Finally Block:

The keyword finally establishes a block that definitely executes the statements placed in it irrespective of whether any exception has occurred or not. That means the statements that are placed in finally block are always going to be executed irrespective of whether any exception is thrown or not, irrespective of whether the thrown exception is handled by the catch block or not.

Syntax to use Exception Handling in C#:

The following image shows the syntax for using exception handling in C#. It starts with the try block, followed by the catch block, and writing the finally block is optional. You can write any number of catch blocks for a given try block in C#. This will handle different types of exceptions thrown by the try block.

Syntax to use Exception Handling in C#

Once we use the try-and-catch blocks in our code, the execution takes place as follows:

  1. Suppose all the statements under the try block are executed successfully, from the last statement of the try block. In that case, the control directly jumps to the first statement present after the catch block (after all catch blocks) without executing the catch block (it means there is no runtime error in the code).
  2. Suppose any of the statements in the try block causes an error from that statement without executing any other statements in the try block. In that case, the control directly jumps to the catch blocks, which can handle that exception.
  3. If a proper catch block is found that handles the exception thrown by the try block, then the abnormal termination stops there, executes the code under the catch block, and from there again, it jumps to the first statement after all the catch blocks.
  4. If a matching catch block is not found, the generic catch block will execute to handle the abnormal termination.
  5. If you don’t have the generic catch block and any of the catch blocks cannot handle the exception, the program execution terminates abnormally.

Note: Here, we are showing the try-and-catch block execution. Later in our upcoming videos, we will discuss the need and use of finally block in C#.

Example to Handle an Exception using Try-Catch Implementation with Generic Catch Block in C#

The catch block without exception class is called a generic catch, and the generic catch block in C# can handle any exception raised in the corresponding try block. For a better understanding, please have a look at the below example. Here, we created the catch block without any Exception class.

using System;
namespace ExceptionHandlingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int Number1, Number2, Result;
            try
            {
                Console.WriteLine("Enter First Number:");
                Number1 = int.Parse(Console.ReadLine());
                Console.WriteLine("Enter Second Number:");
                Number2 = int.Parse(Console.ReadLine());
                Result = Number1 / Number2;
                Console.WriteLine($"Result = {Result}");
            }
            catch
            {
                Console.WriteLine("Some Error Occurred...");
            }
            Console.ReadKey();
        }
    }
}

Output1: Enter the value as 10 and 0

Exception Handling in C#

Output2: Enter the value as 10 and abc

Exception Handling in C# with Examples

In the above example, no exception class is used in the try block, which is known as the generic catch block. The problem with the generic catch block is that if any kind of exception occurs, the same message will be displayed to the end user, and the end user cannot understand why the error has occurred; to overcome this, specific catch blocks are used. Using specific catch blocks, it is possible to learn more about the exception.

Properties of Exception Class in C#:

The Exception Class is the superclass of all Exception classes, providing some virtual properties and methods which are re-implemented by the child classes. If you go to the definition of the Exception class, then you will see the following.

Exception Class in C#

Some of the important properties of the Exception Class are properties as follows:

  1. Message: This property will store the reason why an exception has occurred.
  2. Source: This property will store the application’s name from which the exception has been raised.
  3. HelpLink: This is used to provide a link to any file /URL to give helpful information to the user about why this exception is raised.
  4. StackTrace: This is used to provide more information about the Exception, such as the reason for the exception, what method and class the exception occurred in, and what line number the exception occurred at, which helps us resolve the issue.
Exception Handling in C# using Try-Catch Implementation with Exception Catch Block

In the below example, we have created a catch block that takes the Exception class as a parameter. Within the catch block, we print the exception information using the Exception class properties, i.e., Message, Source, StackTrace, and Helplink. As you can see in the below code, we are using the super Exception class. This class is the superclass of all exception classes so that it will handle all types of exceptions raised in the try block.

using System;
namespace ExceptionHandlingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int Number1, Number2, Result;
            try
            {
                Console.WriteLine("Enter First Number:");
                Number1 = int.Parse(Console.ReadLine());
                Console.WriteLine("Enter Second Number:");
                Number2 = int.Parse(Console.ReadLine());
                Result = Number1 / Number2;
                Console.WriteLine($"Result = {Result}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Message: {ex.Message}");
                Console.WriteLine($"Source: {ex.Source}");
                Console.WriteLine($"HelpLink: {ex.HelpLink}");
                Console.WriteLine($"StackTrace: {ex.StackTrace}");
            }
            Console.ReadKey();
        }
    }
}

Output1: Enter the value as 10 and 0

Exception Handling in C# using Try-Catch Implementation with Exception Catch Block

Output2: Enter the value as 10 and abc

Exception Handling in C# using Try-Catch Implementation with Exception Catch Block

The Exception superclass handles all exceptions thrown from the corresponding try block in the above example. However, using the super Exception class when a relevant child exception class is available will kill the program’s execution performance. So, in the next video, I will show you how to implement multiple catch blocks to handle different exceptions.

In the next article, I will discuss how to use Multiple Catch Blocks and Finally Block in C# with Examples. In this article, I will try to explain Exception handling in C# with Examples. I hope you understand how to implement Exception Handling in C# with Examples. 

8 thoughts on “Exception Handling in C#”

  1. I think this:
    “But if we use the super Exception class when there is any relevant class is available, it will kill the execution performance of the program.”

    wants to say this:

    “But if we use the super Exception class when there is no relevant class available, it will kill the execution performance of the program.”

  2. So we need to define super Exception class in catch block after other sub-exception class. Like switch-case super Exception will play like “default”.

  3. Then what you will do? You might be contacted with the bank, you might be going to the nearest bank and investigating what happens, Why the money is deducted from my account, and why it is not added to the destination account. This is the problem and this very dangerous and this is because we are not handling the runtime errors in our application.

    not is last line is changing the meaning of whole statement and I think its mistake, Please correct me If I am wrong.

Leave a Reply

Your email address will not be published. Required fields are marked *