Exception & Exception Handling in C#
This topic is prepared to keep in mind at the point of interview as how an interviewer can ask one by one question in deep to know how deep knowledge you have. let start from rudimentary.
Qst 1.
What is an Exception and its types.
Exception is a type of error(s) that occurs during the execution of an application, Errors are typically problem that are not expected.
There are two types of exception in .Net
a). System exception : Occurred by the CLR.
b). Application Exception Occurred by the custom code written by user(programmer).
Some system exception list given below with description.
Exception Class |
Description (Cause) |
SystemException |
A failed run-time check;used as a base class for other. |
AccessException |
Failure to access a type member, such as a method or field. |
ArgumentException |
An argument to a method was invalid. |
ArgumentNullException |
A null argument was passed to a method that doesn't accept it. |
ArgumentOutOfRangeException |
Argument value is out of range. |
ArithmeticException |
Arithmetic over - or underflow has occurred. |
ArrayTypeMismatchException |
Attempt to store the wrong type of object in an array. |
BadImageFormatException |
Image is in the wrong format. |
DivideByZeroException |
An attempt was made to divide by zero. |
FormatException |
The format of an argument is wrong. |
IndexOutOfRangeException |
An array index is out of bounds. |
InvalidCastExpression |
An attempt was made to cast to an invalid class. |
InvalidOperationException |
A method was called at an invalid time. |
MissingMemberException |
An invalid version of a DLL was accessed. |
NotFiniteNumberException |
A number is not valid.
|
NotSupportedException |
Indicates sthat a method is not implemented by a class. |
NullReferenceException |
Attempt to use an unassigned reference. |
OutOfMemoryException |
Not enough memory to continue execution. |
StackOverflowException |
A stack has overflown. |
Qst 2.
Why we need exception handling how to handle exception. Give an real time example?
Ans. To stop the abnormal termination of the program, and also provide user understandable messages when an exception is raised. So that users can make the decision without the help of developers.
C# provides built-in support to handle the exception using try, catch & finally block.
try
{
// code that may raise exceptions
}
catch(Exception ex)
{
// handle exception
}
finally
{
// final cleanup code.
}
There is lot of example one of them is in case of excel import of attendance data of employees where empid , attenddate field is there suppose those employee is present there's attenddate and time are filled and those employees absent there's data is empty.
Now when you are importing data if all employees are preset then data imported successfully, but in case of at least one employee absent, then system gives exception because datetime conversion exception not handled.
Once you have handle exception it is import fine to give default date value.
using System;
using System.Data;
class ExceptionThrowNThrowex
{
public static void Main()
{
DataTable dtExcelData = GetData();
DataTable dtProcessed = new DataTable();
dtProcessed.Columns.AddRange(new DataColumn[]
{
new DataColumn("EmpID",typeof(short)),
new DataColumn("AttendDate", typeof(DateTime)),
});
foreach (DataRow row in dtExcelData.Rows)
{
DataRow dr = dtProcessed.NewRow();
dr["EmpID"] = row["EmpID"];
dr["AttendDate"] = row["AttendDate"];
dtProcessed.Rows.Add(dr);
}
Console.ReadLine();
}
/// <summary>
/// Make data manullay, in real time scenario these data will come from excel.
/// </summary>
/// <returns>DataTable</returns>
static DataTable GetData()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("EmpID",typeof(string)),
new DataColumn("AttendDate", typeof(string))
});
DataRow dr = dt.NewRow();
dr["EmpID"] = "1";
dr["AttendDate"] = "2020-03-29 09:34:22.193";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["EmpID"] = "2";
dr["AttendDate"] = "2020-03-29 09:35:22.193";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["EmpID"] = "3";
dr["AttendDate"] = "";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["EmpID"] = "4";
dr["AttendDate"] = "2020-03-29 09:35:22.193"; ;
dt.Rows.Add(dr);
return dt;
}
}
Output is Crashes application.
Once you handle Exception like .
using System;
using System.Data;
class ExceptionThrowNThrowex
{
public static void Main()
{
DataTable dtExcelData = GetData();
DataTable dtProcessed = new DataTable();
dtProcessed.Columns.AddRange(new DataColumn[]
{
new DataColumn("EmpID",typeof(short)),
new DataColumn("AttendDate", typeof(DateTime)),
});
foreach (DataRow row in dtExcelData.Rows)
{
try
{
DataRow dr = dtProcessed.NewRow();
dr["EmpID"] = row["EmpID"];
dr["AttendDate"] = row["AttendDate"];
dtProcessed.Rows.Add(dr);
}
catch
{
DataRow dr = dtProcessed.NewRow();
dr["EmpID"] = row["EmpID"];
dr["AttendDate"] = "1 jan 1900";
dtProcessed.Rows.Add(dr);
}
}
foreach (DataRow dr in dtProcessed.Rows)
{
string AttendDate = Convert.ToDateTime(dr["AttendDate"]).ToString("dd MMM yyyy");
Console.WriteLine("EmpID : " + dr["EmpID"] + ", IsPresent : " + ( Convert.ToDateTime(dr["AttendDate"]).ToString("dd MMM yyyy") == "01 Jan 1900" ? "No" : "Yes" ) + " ,AttendTime" + dr["AttendDate"]);
}
Console.ReadLine();
}
Output
Qst 3.
Explain the difference between Error and Exception in C#?
Exceptions are those which can be handled at the runtime whereas errors cannot be handled.
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.
Qst 4 .
What is order of Try - Catch - Finally Blocks?.
Ans. Order of exception handling , try block comes first after that catch block and at last finally block get executed.
Qst 5.
Can a try block exists without catch or Finally block ?.
Ans . No. At least one of them is required to run code and we can also have both block at a time. let see an example
using System;
class MainProgram
{
static void Main(string[] args)
{
Devision();
Console.ReadLine();
}
static void Devision()
{
try
{
int InputNo;
InputNo = Convert.ToInt32(Console.ReadLine().ToString());
int module = 100 / InputNo;
}
}
}
If you are trying to run code it will give Compile time error.
Error CS1524 Expected catch or finally.
A try block have at least one catch block or finally block, hence combination of try-catch-finally or try catch or try-finally blocks is valid.
Qst 6.
Can a try block have multiple catch block ?.
Ans . Yes. let see an example
using System;
class MainProgram
{
static void Main(string[] args)
{
Devision();
Console.ReadLine();
}
static void Devision()
{
try
{
int InputNo;
InputNo = Convert.ToInt32(Console.ReadLine().ToString());
int module = 100 / InputNo;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Exception :" + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Exception :" + ex.Message);
}
}
}
It is running perfect.
Qst 7.
Can a try block has catch and finally block both?.
Ans . Yes.
Qst 8.
might possibility an interviewer can ask to given bellow scenario.
.........
........ in continuation
catch (Exception Ex)
{
Console.WriteLine("Exception :" + ex.Message);
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
as we explained more than one catch block is possible. Is this code is running perfect or give any error?.
Ans. It will give error at compile time
Error CS0160 A previous catch clause already catches all exceptions of this or of a super type ('Exception')
Because 'Exception' is parent class of all exception handling class and it will never go to next catch block. hence more specialized catch block should come before a generalized one. other wise specialized catch block will never be executed ( dot net frame not allowed the same.)
Qst 9.
Next question arises that will finally block execute if try or catch block has return statement or gives exception in try or catch block.
Ans. finally block will always execute whether try and catch block have return statement.
since generally finally block used to memory management to destroy object which was created earlier.
Qst 10.
What happened if error occurred in finally block?.
Ans. If error occurred in finally block cursor leave finally block nothing will executed further.
Qst 11.
Can finally return value?.
Ans. No .
finally
{
return 1; // Gives compile time error 'control can not leave the body of finally clause'
}
because finally block is used for cleanup resources so that the control can not be exit without its completion.
Qst 12.
What is inner or nested exception?.
Ans. An exception will be caught in the catch block that follows the try block where an exception occurred.
using System;
public class NestedClass
{
public static void Main()
{
try
{
try
{
int[] arr = { 2, 4, 5, 6, 7 };
var intdata = arr[6];
}
catch (IndexOutOfRangeException innerEx)
{
Console.WriteLine("Inner Exception " + innerEx.Message.ToString());
int z = 0;
z = Convert.ToInt32(Console.ReadLine());
if (z != 0)
{
var i = 100 / z;
}
else
{
throw new DivideByZeroException("Invalid OPeration Divide by Zero ", innerEx);
}
}
}
catch (DivideByZeroException OuterEx)
{
Console.WriteLine("Outer Exception : " + OuterEx.Message + ", Inner Exception : " +OuterEx.InnerException);
}
Console.ReadLine();
}
}.
Enter Zero hit enter it will give following result.
Qst 13.
What is Application or Custom exception.
Ans. Custom exception is application level exception that is created by developer to raise an exception when the business rule of your application gets violated or not full fill you criteria what you expected.
using System;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
public class CustomApplicationException
{
public static void Main()
{
string Name = "Ram@123";
try
{
ValidateName(Name);
}
catch (InvalidNameException Ex)
{
Console.WriteLine(Ex.Message.ToString());
}
Console.ReadLine();
}
private static void ValidateName(string Name)
{
Regex regex = new Regex(@"^[a-zA-Z\s]+$");
if (!regex.IsMatch(Name))
{
throw new InvalidNameException(Name);
}
}
}
[Serializable]
internal class InvalidNameException : ApplicationException
{
public InvalidNameException()
{
}
public InvalidNameException(string Name) : base(string.Format("Invalid Name : {0}", Name))
{
}
public InvalidNameException(string message, Exception innerException) : base(message, innerException)
{
}
protected InvalidNameException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
here exception interface has following overload methods.
// Out put
Qst 14 .
What is throw keyword and why use?.
Ans. throw keyword can be used to raised manually exception. throw keyword can raised any type of exception which is derived from exception class like throw new DivideByZeroException , NullreferenceException , FileNotFoundException , Object null Reference Exception.
throw creates an object of any valid exception type using the new keyword. it has three overload method, without parameter , with message , and with messgae and innerexception parameter which was explain in Ans 11.
Example:
using System;
class ExceptionThrowANDex
{
public static void Main()
{
try
{
DevidebyZero(10);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
Console.ReadLine();
}
public static void DevidebyZero(int i)
{
try
{
int j = 0;
int k = i / j;
Console.WriteLine(k);
Console.ReadLine();
}
catch (Exception ex)
{
throw;// check first comment and uncomment see what happen
}
}
}
for a moment lets comment throw keyword in above code what you think will main method catch blog executed. No its not executed because in DevidebyZero method exception handled but not throw
hence in cal lee method catch not executed.
Once you uncomment and run application throw keyword help to raised exception manually in Main method and out put is.
If you want to show some customization message then you can do
int j = 0;
if (j != 0)
{
int k = i / j;
Console.WriteLine(k);
Console.ReadLine();
}
else
{
throw new DivideByZeroException("You are try to devide by Zero Which is not meaning full");
}
Output :
Qst 15. What is Stack Tarce?.
Ans. The execution stack keeps track of all the methods that are in execution at a given instant. A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs.
The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown. You can obtain information about additional frames in the call stack by creating a new instance of the System.Diagnostics.StackTrace class and using its StackTrace.ToString method. Example in Ans 12.
Qst 16. What is difference between throw and throw ex ?.
Ans. throw ex will reset your stack trace so error will appear from the line where throw ex written while throw does not reset stack trace and you will get information about original exception.
In MSIL code when you use throw ex it will generate code as throw , and if you use throw it will create rethrow.
using System;
class ExceptionThrowNThrowex
{
public static void Main()
{
try
{
Console.WriteLine("Please enter number.:");
int i = Convert.ToInt32(Console.ReadLine());
Division(i);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
Console.ReadLine();
}
public static void Division(int i)
{
try
{
Division_Concrete(i);
}
catch (Exception ex)
{
throw ex;// it will reset stack trace of method Division_Concrete exception
}
}
public static void Division_Concrete(int i)
{
try {
if (i == 0)
{
throw new DivideByZeroException("you are trying to divide by zero which is not meaning full");
}
else
{
int k = 100 / i;
Console.WriteLine(k);
}
}
catch(Exception ex)
{
throw;
}
}
}
Output it is working properly.
Now use only throw in place of throw ex in Division(int i) method. and out put
Qst 17. What is Web Exception?.
Ans. The web exception class is thrown by class decedent from WebRequest and WebResponse
when the web exception is thrown by a decedent of the web request class the response property provides the internet response to the application