C# Interview Question and Answers with Example - Part 5


Below is top C# interview question and answers with examples for freshers and intermediate developers.

What is exception in C#?

An exception is an unforeseen error that occurs when a program is running.
Ex:
Trying to read from a file that does not exist, throws FileNotFoundException.
Trying to read from a database table that does not exist, throws a SqlException.

What are the properties of exception class?

Below is the some important properties of exception class.
Message: Provides details about the cause of the exception.
StackTrace: Provides information about where the error occurred.
InnerException: Provides information about the series of exceptions that might have occurred.
HelpLink: This property can hold the help URL for a particular exception.
Data: This property can hold arbitrary data in key-value pairs.
TargetSite: Provides the name of the method where this exception was thrown.

List down some important exception Classes.

ArgumentException: Raised when a non-null argument that is passed to a method is invalid.
ArgumentNullException: Raised when null argument is passed to a method.
ArgumentOutOfRangeException: Raised when the value of an argument is outside the range of valid values.
DivideByZeroException: Raised when an integer value is divide by zero.
FileNotFoundException: Raised when a physical file does not exist at the specified location.
FormatException: Raised when a value is not in an appropriate format to be converted from a string by a conversion method such as Parse.
IndexOutOfRangeException: Raised when an array index is outside the lower or upper bounds of an array or collection.
InvalidOperationException: Raised when a method call is invalid in an object's current state.
InvalidCastException: Raised when incompitible types are being converted.
KeyNotFoundException: Raised when the specified key for accessing a member in a collection is not exists.
NotSupportedException: Raised when a method or operation is not supported.
NullReferenceException: Raised when program access members of null object.
OverflowException: Raised when an arithmetic, casting, or conversion operation results in an overflow.
OutOfMemoryException: Raised when a program does not get enough memory to execute the code.
StackOverflowException: Raised when a stack in memory overflows.
TimeoutException: The time interval allotted to an operation has expired.

What are two main types of exception?

Exception types: SystemException and ApplicationException.

How can you handle the exception?

We can handle the exception using try, catch and finally block.
try: The code that can possibly cause an exception will be in the try block.
catch: Handles the exception.
finally: Clean and free resources that the class was holding onto during the program execution.
try
{
// code that may raise exceptions
}
catch(Exception ex)
{
// handle exception
}
finally
{
// final cleanup code
}

What is inner exception?

The InnerException is a property of an exception. When there are series of exceptions, the most current exception can obtain the prior exception in the InnerException property.

What is use of finally block?

Finally block will always be executed irrescpective of exception occures or not.
Finally block is used to close database connection, release external resources etc.

Can we have multiple catch block?

Yes

What is the order of exception classes with catch block if multiple catch block is present?

Specific exceptions will be caught before the base general exception, so specific exception blocks should always be on top of the base exception block. Otherwise, you will encounter a compiler error.

What will happen if below code is executed?

try
{
int a = 1;
int b = 0;
int output = a/b;
}
catch (Exception ex)
{
}
catch (DivideByZeroException ex)
{
}

It will throw compile time error as Exception class is already handling the all type of exceptions. So, DivideByZeroException exception should be writen first and Exception class written should be in last.

Valid code:
try
{
int a = 1;
int b = 0;
int output = a/b;
}
catch (DivideByZeroException ex)
{
}
catch (Exception ex)
{
}

Will the following code be compiled?

try
{
int a = 1;
int b = 0;
int output = a/b;
}
catch
{
}

Yes

Will the following code be compiled?

try
{
int a = 1;
int b = 0;
int output = a/b;
}
catch
{
}
catch (Exception ex)
{
}

No

Is it necessary to have finally block?

No

Can we have multiple finally block?

No

Can we have return, break or continue keywords in finally block?

No

Can we have nested try-catch block?

Yes

Will the following code be compiled?

try
{
    try
    {
        int a = 1;
        int b = 0;
        b = a / b;
    }
    catch (Exception e)
    {
        throw new FileNotFoundException("hello world", e);
    }
}
catch (Exception ex)
{
}

Yes

Can we have try block without catch block?

Yes
But, try block should be combined with catch block or finally block i.e. (try-catch) or (try-finally).

Will the following code be compiled/run?

try
{
string Test = "hello";
}

No
Compile time error will be thrown. It expects catch or finally block.

What is use of throw keyword?

An exception can be raised manually by using the throw keyword. Any type of exceptions which is derived from Exception class can be raised using the throw keyword.

Difference between throw and throw ex

Throw maintain stacktrace info where as throw ex does not maintain stacktrace info from throw point.

How to create Custom exception in C#?

You can create custom exception by inheriting Exception class in C#.


Page 5 of 7