Exception handling in C# - ProgramIdea

Exception Handling in C#


When program is executing then at runtime error may be occur due to wrong data type conversion, passing invalid connection string, permission failed while opening a file and there are lots of condition. Error which is occurred at runtime is known as exception. Exception will cause abnormal termination of program execution, if no exception handler present for a given exception, then the program terminate abnormally and stops execution with an error details. This is very bad impression on user so in that condition we use exception handling mechanism in .Net application.

Exceptions are type that all derive from System.Exception class.

try catch block

The try section contains the statements that might throw an exception. A catch block used to handle exception which is raise in try block. When our code executes and on that time, if any line of statement of try block throwing an exception, then following line of execution statement are ignored and control directly jumps to catch block and execute catch block. A try block can be followed by multiple catch sections. Writing an exception class with in the catch block is optional.

Simple try-catch block

// Simple try-catch block 

try
{
    // Your logical codes
}
catch (Exception Ex)
{ 

}

Multiple catch blocks

//Multiple catch blocks for one try block
try
{
    // Your logical codes
}
catch (DivideByZeroException Ex)
{ 

}
catch (OverflowException Ex)
{ 

}
catch (FormatException Ex)
{

}

Nested try-catch blocks

// Nested try-catch block
    try
    {
        // Your logical codes

        try
        {
        // Your logical codes
        }
        catch (Exception Ex)
        { 

        }
    }
    catch (Exception Ex)
    { 

    }

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

 // generic catch block
try
{
    // Your logical codes
}
catch
{
    Console.Write("Exception raised in the application");
}

finally block

A finally block enables you to clean up actions that are performed in a try block. The finally block can be used to release resources such as a file streams, database connections and graphics handlers without waiting for the garbage collector in the runtime to finalize the object. You can use finally block with only try block without using catch block.

The finally section always executes, even if the program leaves the try and catch sections because of any reasons:

try section executes and no catch section execute.

try section raised exception and catch section handle it.

try section raised exception and that not caught by any catch section

catch section throw an exception

try section uses a return statement to exit the method

catch section uses return statement to exit the method

// try-catch-finally blocks
try
{
    // Your logical codes
}
catch (Exception Ex)
{ 

}
finally
{    

}

throw

If you catch the exception in catch block, then throwing it by using the throw keyword at the end of catch block. Exception can be explicitly generated by a program using throw keyword.

Explicitly generate exception

int a = -1; 

if (a < 0)
{
    throw new System.ArgumentException( "Application can not accept negative values" );
}

Exception throwing

When the code throws an exception in this way, the exception's call stack is reset to the current location so that it refers to the line of code that contains the throw statement. That may mislead any programmers who try to locate a problem by making them look at the wrong line of code. The situation is even worse if the line of code that throw the exception as inside another method called by this one. If you rethrow the exception in this way, the fact that the error is in another method is lost.

In all cases a method should clean up as much as possible before throwing or rethrowing an exception. Before throwing or rethrowing please close file or database connection if they opened.

Please do not throw following exceptions intentionally from your own source code.

System.Exception,

System.SystemException,

System.NullReferenceException,

System.IndexOutOfRangeException

protected void Page_Load(object sender, EventArgs e)
{
    Test();
}
public void Test()
{
    try
    {
        CheckInt();
    }
    catch (Exception Ex)
    {
        Response.Write("Message -"+Ex.Message + "<br/>");
        Response.Write("Source - "+Ex.Source + "<br/>");
        Response.Write("StackTrace - "+Ex.StackTrace + "<br/>");         
    }
}

public void CheckInt()
{
    try
    {
        int a = Convert.ToInt32("one");
    }

    catch (Exception Ex)
    {
        throw;
    }
}

Exception rethrowing

protected void Page_Load(object sender, EventArgs e)
{
    Test();
}
public void Test()
{
    try
    {
        CheckInt();
    }
    catch (Exception Ex)
    {
        Response.Write("Message -"+Ex.Message + "<br/>");
        Response.Write("Source - "+Ex.Source + "<br/>");
        Response.Write("StackTrace - "+Ex.StackTrace + "<br/>"); 
    }
}
public void CheckInt()
{
    try
    {
        int a = Convert.ToInt32("one");
    }
    catch (Exception Ex)
    {
        throw Ex;
    }
}
// Message -Input string was not in a correct format.
// Source - App_Web_exception-handling.aspx.97720aef.zyrdtxtq
// StackTrace - at CSharp_Exception_Handling.CheckInt() in d:\ProgramIdea\CSharp\Exception-Handling.aspx.cs:line 36
// at CSharp_Exception_Handling.Test() in d:\ProgramIdea\CSharp\Exception-Handling.aspx.cs:line 18

Exception Properties

Property Description
Message A message explaining about the exception in general terms.
Source The name of the application or object that caused the exception.
StackTrace A string representation of the program's stack trace when the exception occurred. It also containing code's line number that generated exception.
TargetSite Information about the method that throw the exception.
InnerException An exception object that gives more information about the exception
Data A collection of key-value pairs that give information about the exception.
Helplink A link to a help file associate with the exception.
HResult A numeric code describing the exception in general terms.