Exception Handling Interview Questions in C#

Exception Handling Interview Questions in C# with Answers

In this article, I am going to discuss the most frequently asked Exception Handling Interview Questions in C# with Answers. Please read our previous article where we discussed the most frequently asked Deadlock Interview Questions in C# with Answers. As part of this article, we are going to discuss the following Exception Handling Interview Questions in C# with Answers.

  1. Explain different types of errors in C#.
  2. What is a Compilation Error and Runtime Error in C#?
  3. What is an Exception?
  4. Who is responsible for abnormal termination of the program whenever runtime errors occur?
  5. What happens if an exception is raised in the program?
  6. What CLR does when a logical mistake occurred in the program?
  7. Explain Exception Handling?
  8. Why we need exception handling?
  9. What is the Exception Handling Procedure?
  10. How can we handle the exception in .NET?
  11. Explain the difference between Error and Exception in C#?
  12. What is the difference between System exceptions and Application exceptions?
  13. Explain about try-catch implementation.
  14. Explain the Different Properties of the Exception class in C#.
  15. Can we catch all exceptions using a single catch block?
  16. When should we write multiple catch blocks for a single try block?
  17. Explain about the finally block
  18. Why we need finally block in the real-time project?
  19. How many ways we can use try-catch and finally?
  20. What happens if the finally block throws an exception?
  21. What is the difference between the “throw” and “throw ex” in .NET?
  22. What is Inner Exception?
Explain different types of errors in C#.

When we write and execute our code in the .NET framework then there is possible of three types of error occurrences they are

  1. Compilation errors
  2. Runtime errors
What is a Compilation Error in C#?

An error that occurs in a program at the time of compilation is known as the compilation error. These errors occur due to syntax mistakes under the program.

These errors occur by typing the wrong syntax like missing double quotes and terminators, typing wrong spelling for keywords, assigning wrong data to a variable, trying to create an object for abstract class and interface, etc.

That means this error occurs due to the poor understanding of the programming language. These errors can be identified by the programmer and can be rectified before the execution of the program only. So these errors do not cause any harm to the program execution.

What is Runtime Error in C#?

The errors which are occurred at the time of program execution are called as a runtime error. These errors are like entering wrong data into a variable, trying to open a file for which there is no permission, trying to connect to the database with wrong user id and password, the wrong implementation of logic, missing of required resources, etc.

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

What is an Exception?

A runtime error is known as an exception. An exception cannot be identified and rectified by the programmer. The exception will cause abnormal termination of the program execution.

So these errors (exceptions) are very dangerous because whenever an exception occurs in the programs the program gets terminated abnormally on the same line where the error gets occurred without executing the next line of code.

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

The Objects of exception classes are responsible for abnormal termination of the program whenever runtime errors occur. These exception classes are predefined under BCL where a separate class is provided for each and 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 specific exception error message.

All exception classes are responsible for abnormal termination of the program as well as after abnormal termination of the program they will be displaying an error message which specifies the reason for abnormal termination i.e. they provide an error message specific to that error.

Whenever a runtime error occurs in a program, first the exception manager under CLR identifies the type of error that occur in the program, creates an object of the exception class related with that error and throws that object which will immediately terminate the program abnormally on the line where error got occur and display the error message related with that class.

What happens if an exception is raised in the program?

Program execution is terminated abnormally. It means statements placed after exception causing statement are not executed but the statements placed before that exception causing statement are executed by CLR.

What CLR does when a logical mistake occurred in the program?

This is one of the frequently asked Exception Handling Interview Questions in C#.

It creates an exception class object that is associated with that logical mistake and terminates the current method 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.

Below program shows program execution without exception:

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();
        }
    }
}
Below program shows program execution with exception:
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:
a value = 20
b value = 0
DivideByZeroException was unhandled Attempt to divide by zero.

Explanation: CLR terminates this program execution by throwing DivideByZeroException because the logical mistake we committed is dividing integer number by integer zero. As we know it is not possible to divide an integer number by zero.

From the above program, we can define the exception technically as “An exception is an event because when an exception is raised CLR internally executes some logic to prepare that exception related messages”.

The exception is a signal because by looking into exception message developer will take necessary actions against that exception. An exception is an object because for throwing exception CLR or we should create an appropriate class object.

Is the above exception message is user understandable?

Definitely, no, the user cannot understand the above exception message because they are .NET based exception messages. So the user cannot take further decision alone to resolve the above problem. The developer should guide to solve the above problem.

What is the solution for the above problem?

It is developer responsibility to convert .NET exception messages into user understandable message format. To solve this problem developer should write exception handling code in a .NET program. Using exception handling code, the developer can catch the exception and can print and pass user understandable messages.

What is Exception Handling in C#?

This is one of the frequently asked Exception Handling Interview Questions in C#.

The process of catching the exception for converting CLR given exception message to end-user understandable message or for stopping the abnormal termination of the program whenever runtime errors are occurring is called exception handling. Once we handle an exception under a program we will be getting following advantages

  1. We can stop the abnormal termination
  2. We can perform any corrective action that may resolve the problem occurring due to abnormal termination.
  3. Displaying a user-friendly error message, so that the client can resolve the problem provided if it is under his control.
Why we need exception handling in C#?

In projects, an exception is handled

  1. To stop the abnormal termination of the program
  2. To provide user understandable messages when an exception is raised. So that users can make the decision without the help of developers.

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

What is the Exception Handling Procedure?

Exception handling is a 4 steps procedure

  1. Preparing the exception objects 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 the exception in .NET?

There are three methods to handle the exception in .NET

  1. Logical implementation
  2. Try catch implementation
  3. On error go to implementation
Explain the difference between Error and Exception in C#?

This is one of the frequently asked Exception Handling Interview Questions in C#.

Exceptions are those which can be handled at the runtime whereas errors cannot be handled.

An exception is an object of a type deriving from the System.Exception class. The exception is thrown by the CLR (Common Language Runtime) when errors occur that are nonfatal and recoverable by user programs. It is meant to give you an opportunity to do something with a throw statement to transfer control to a catch clause in a try block.

The error is something that most of the time we cannot handle it. Errors are the unchecked exception and the developer is not required to do anything with these. Errors normally tend to signal the end of our program, it typically cannot be recovered from and should cause us to exit from the current program. It should not be caught or handled.

All the Errors are Exceptions but the reverse is not true. In general, Errors are which nobody can control or guess when it happened on the other hand Exception can be guessed and can be handled.

What is the difference between System exceptions and Application exceptions?

System exceptions are derived directly from a base class System.SystemException. A System-level Exception is normally thrown when a nonrecoverable error has occurred.

Application exceptions can be user-defined exceptions thrown by the applications. If you are designing an application that needs to create its own exceptions class, you are advised to derive custom exceptions from the System.ApplicationException class. It is typically thrown when a recoverable error has occurred.

What is the logical implementation?

In this method, we handle the exception by using logical statements. In real-time programming, the first and foremost important always given to logical implementation. If it is not possible to handle an exception using logical implementation then we use try-catch implementation.

Program to handle an exception using logical implementation.

namespace ExceptionHandlingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            b = int.Parse(Console.ReadLine());
            int a, b, c;
            Console.WriteLine("ENTER ANY TWO NUBERS");
            a = int.Parse(Console.ReadLine());
            if (b == 0)
            {
                Console.WriteLine("second number should not be zero");
            }
            else
            {
                c = a / b;
                Console.WriteLine("C VALUE = " + c);
            }
            Console.ReadKey();
        }
    }
}

In the above example when the user entered the second number as zero exception will be raised and that is handled using logical implementation.

But while we are entering two numbers instead of the number if we entered any character then it will give you one exception that FormatException which is not handled in this program. So to handle such type of exception we need to go for Try catch implementation.

Explain about try-catch implementation.

To implement the try-catch implementation .NET provides three keywords

  1. Try
  2. Catch
  3. finally

try: try keyword establishes a block in which we need to write the exception causing and its related statements. That means exception causing statements must be placed in the try block so that we can handle and catch that exception for stopping abnormal termination and to display end-user understandable messages.

Catch: The catch block is used to catch the exception that is thrown from its corresponding try block. It has logic to take necessary actions on that caught exception.

Catch block syntax looks like a constructor. It does not take accessibility modifier, normal modifier, return type. It takes a single parameter of type Exception.

Inside catch block, we can write any statement which is legal in .NET including raising an exception. If the catch block is used without an exception class then it is known as a generic catch block. If the catch block is used with exception class then it is known as a specific catch block.

Finally: Finally establishes a block that definitely executes statements placed in it. Statements that are placed in finally block are always executed irrespective of the way the control is coming out from the try block either by completing normally or throwing an exception by catching or not catching.

SYNTAX TO USE TRY CATCH:

Exception Handling Interview Questions in C# with Answers

Once we enclose the code under try and catch blocks the execution takes place as following

If all the statements under try are executed successfully from the last statement of trying the control directly jumps to the first statement that is present after the catch block (after all catch blocks) without executing catch block (it means there is no runtime error in the code at all ).

If any of the statements in the try causes an error from that statement without executing any other statements in try control directly jumps to the catch blocks searching for a catch block to handle that exception.

If a proper catch block is available that can handle the exception and 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. If a matching catch is not available abnormal termination occurs again.

Explain the Properties of the Exception class.

The exception class has 3 properties are as follows

  1. Message: This property will store about the reason why the exception has occurred.
  2. Source: This store name of the application from where 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 when an exception is raised.

Example to show the use of Exception (superclass of all exception classes) class as an argument in catch blocks.

Experienced Interview Questions and Answers in C#

In the above example, the superclass exception is used to handle the exception. But if we use super of any exception class when there is any relevant class is available, it will kill the execution performance of the program. So any time doesn’t use the superclass of an exception class to handle an exception when there is a relevant exception class is available.

Can we catch all exceptions using a single catch block?

Yes, we can catch all exceptions with a single catch block with parameter “Exception”. We should use this catch block only for stopping abnormal termination irrespective of the exceptions thrown from its corresponding try block.

It is always recommended to write catch blocks with exception parameters even though we are writing multiple catch blocks. It acts as a backup catch block.

When should we write multiple catch blocks for a single try block?

We should write multiple catch blocks for a single try block because of the following reasons

  1. To print message specific to an exception or
  2. To execute some logic specific to an exception
Explain about the finally block.

Finally establishes a block that definitely executes statements placed in it. The Statements which are placed in finally block are always executed irrespective of the way the control is coming out from the try block either by completing normally or throwing the exception by catching or not catching.

Why we need finally block in the real-time project?

As per coding standard in finally block we should write resource releasing logic or clean up the code. Resource releasing logic means un-referencing objects those are created in the try block. For example, in real time projects, we create ADO.NET objects in the try block and at the end of the try block, we must close these objects.

Since the statements written in try and catch block are not guaranteed to be executed we must place them in finally block. For example, if we want to close ADO objects such as Connection object, Command object, etc. we must call the close() method in both try as well as in catch block to guarantee its execution.

Instead of placing the same close() method call statements in multiple places if we write it in finally block it is always executed irrespective of the exception raised or not raised.

How many ways we can use try catch and finally?

In can use in three different combinations

  1. Try and catch: In this case, execution will be handled and stopping the abnormal termination.
  2. The Try, catch and finally: In this case also exception will be handled stopping the abnormal termination along with the statements that are placed within the finally block gets executed at any cost.
  3. Try and finally: In this case abnormal will not stop when a runtime error occurs because exceptions are not handled but even if the abnormal termination occurs also finally blocks get executed.
What happens if the finally block throws an exception?

The exception propagates up and should be handled at a higher level. If the exception is not handled at a higher level, the application crashes. The “finally” block execution stops at the point where the exception is thrown. 

In the example below, notice that the “finally” block in the “Hello()” method throws an exception. Hello() method is being called in the Main() method and we don’t have any exception handling mechanism in place in the Main() method. So, the application crashes with the exception.

public class Program
{
    public static void Main()
    {
        Hello();
    }

    public static void Hello()
    {
        try
        {
            // Some code
        }
        catch
        {
            // Some code
        }
        finally
        {
            Console.WriteLine("This line will be executed");
            int result = Convert.ToInt32("TEN");
            Console.WriteLine("This line will NOT be executed");
        }
    }
}

On the other hand, if you include exception handling mechanism(try/catch) in the Main() method, then you will have the opportunity to handle the exception.

public static void Main()
{
    try
    {
        Hello();
    }
    catch (Exception ex)
    {
        // Process and log the exception
        Console.WriteLine(ex.Message);
    }
}
Irrespective of whether there is an exception or not “finally” block is guaranteed to execute. 
  1. If the “finally” block is being executed after an exception has occurred in the try block, 
  2. and if that exception is not handled
  3. and if the finally block throws an exception

Then the original exception that occurred in the try block is lost.

Here is an example:

public class Program
{
    public static void Main()
    {
        try
        {
            Hello();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    public static void Hello()
    {
        try
        {
            // This exception will be lost
            throw new Exception("Exception in TRY block");
        }
        finally
        {
            throw new Exception("Exception in FINALLY block");
        }
    }
}
What is the difference between the “throw” and “throw ex” in .NET?

throw re-throws the exception that was caught, and preserves the stack trace. throw ex-throws the same exception, but resets the stack trace to that method. Unless you want to reset the stack trace (i.e. to shield public callers from the internal workings of your library), the throw is generally the better choice, since you can see where the exception originated.

Throw Syntax:

try
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw;
}

//Throw ex Syntax:
try
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw ex;
}

What is Inner Exception?

The InnerException property returns the Exception instance (original exception) that caused the current exception.

To look at the inner exception, we have to make this program cause an exception to fail. To do that you have 3 options

  1. Enter a Character instead of a number (Causes Format Exception)
  2. Or Enter a very big number that an integer cannot hold (Causes Over Flow Exception)
  3. Or Enter Zero for Second Number (Causes Divide By Zero Exception)
class ExceptionHandling
{
    public static void Main()
    {
        try
        {
            try
            {
                Console.WriteLine("Enter First Number");
                int FN = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter Second Number");
                int SN = Convert.ToInt32(Console.ReadLine());

                int Result = FN / SN;
                Console.WriteLine("Result = {0}", Result);
            }
            catch (Exception ex)
            {
                string filePath = @"C:\Sample Files\Log.txt";
                if (File.Exists(filePath))
                {
                    StreamWriter sw = new StreamWriter(filePath);
                    sw.Write(ex.GetType().Name + ex.Message + ex.StackTrace);
                    sw.Close();
                    Console.WriteLine("There is a problem! Plese try later");
                }
                else
                {
                    //To retain the original exception pass it as a parameter
                    //to the constructor, of the current exception
                    throw new FileNotFoundException(filePath + " Does not Exist", ex);
                }
            }
        }
        catch (Exception ex)
        {
            //ex.Message will give the current exception message
            Console.WriteLine("Current or Outer Exception = " + ex.Message);

            //Check if inner exception is not null before accessing Message property
            //else, you may get Null Reference Excception
            if (ex.InnerException != null)
            {
                Console.WriteLine("Inner Exception = ", ex.InnerException.Message);
            }
        }
    }
}

Here, in this article, I try to explain the most frequently asked Exception Handling Interview Questions in C# with Answers. I hope you enjoy this Exception Handling Interview Questions in C# with Answers article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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