Advanced Exception Handling Interview Questions C#.NET

Exception Handling Interview Questions and Answers

In this article, I am going to discuss most frequently asked Exception Handling Interview Questions and Answers on C#.NET.

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 which 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.

WAP to show the use of Exception (super class of all exception classes) class as argument in catch blocks.

namespace ExceptionHandlingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, c;
            Console.WriteLine("ENTER ANY TWO NUBERS");
            try
            {
                a = int.Parse(Console.ReadLine());
                b = int.Parse(Console.ReadLine());
                c = a / b;
                Console.WriteLine("C VALUE = " + c);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.Source);
                Console.WriteLine(ex.HelpLink);
            }
            Console.ReadKey();
        }
    }
}

In the above example, 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 superclass of an exception class to handle an exception when there is 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 block with exception parameter even though we are writing multiple catch blocks.

It acts as 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.

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 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 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.

In 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 gets 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 the 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 “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);
            }
        }
    }
}
SUMMARY

In this article, I try to explain most frequently asked Exception Handling Interview Questions and Answers on C#.NET. I hope this article will help you with your need. 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 *