Basic Exception Handling Interview Questions C#.NET

Basic Exception Handling Interview Questions and Answers

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

Explain about different types of errors?

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?

An error that occurs in a program at the time of compilation of a program 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?

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 get 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 in the program?

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?

It creates exception class object that is associated with that logical mistake and terminates the current method execution by throwing that exception object by using “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();
        }
    }
}

Output:

a value = 20

b value = 10

c value = 2

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 the 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?

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

We can stop the abnormal termination

We can perform any corrective action that may resolve the problem occurring due to abnormal termination.

Displaying a user-friendly error message, so that client can resolve the problem provided if it is under his control.

Why we need exception handling?

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 user can take the decision without developers help.

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 exception object 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#?

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 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 the 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 implements 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 only single parameter of type Exception.

Inside catch block, we can write any statement which is legal in .NET including raising an exception.

If catch block is used without an exception class then it is known as a generic catch block.

If catch block is used with exception class then it is known as specific catch block.

Finally:

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 exception by catching or not catching.

SYNTAX TO USE TRY CATCH:

void m1()
  {
    ----------------
    ----------------//normal statements
    try
    {
      ---------------
      ----------------//exception causing and its related statements which does not required    
      ----------------//execution when the runtime errors occur
    }
    catch(SomeException1 one)
    {
      -----------------//statements which requires execution only when the run time errors 
      ------------------// occurs in the program
      
    }
    catch(SomeException2 two)
    {
      -----------------//statements that takes proper actions against
      ---------------- //SomeException2
      
    }
    ----------------
    ----------------//normal statements
  } 
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 try 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 statement 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.

Program to handle an exception using try catch implementation with generic catch

NOTE: catch block without exception class is called as generic catch and this catch block can handle any type of exception that is raised in the corresponding try block.

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
            {
                Console.WriteLine("error occured....");
            }
            Console.ReadKey();
        }
    }
}

In the above example, there is no exception class used in the try block, so it is known as generic catch block.

But in the above example, any kind of exception may occur the same message will be displayed to the user and user cannot understand why the error has occurred, to overcome this specific catch blocks are used.

Using specific catch blocks it is possible to know more information about the exception.

SUMMARY

In this article, I try to explain most frequently asked Basic 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 *