Learning Exception Handling in C# with 8 Tips

No.of Views1144
Bookmarked1 times
Downloads 
Votes0
By  Vishal Nayan   On  28 Apr 2011 08:04:12
Tag : CSharp , Exception Handling
Exceptions are unforeseen errors that happen in our programs. Most of the time, we can, and should, detect and handle program errors in your code. Exception is handling is in build feature of.NET framework which find the errors and helps us in handling them.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Exceptions are unforeseen errors that happen in our programs. Most of the time, we can, and should, detect and handle program errors in your code. Exception is handling is in build feature of.NET framework which find the errors and helps us in handling them.

Difference between Bug, Error and defect:

Error: Is a fault in the program, syntax or execution.

There are three types of errors

1)    syntactical error: it is deviation from syntax of program
2)    Logical error: it is deviation from logic of the program.
3)    Execution error: this occurs during executing the program.

Defect: when the error is discovered by the tester then it is called defect.
Bug: If the developer accepts the defect then it is called bug.

Namespace to add: System.Exception

The System.Exception class provides several methods and properties for obtaining information on what went wrong. System.Exception is the base class for all exceptions in C#.
Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions.

1)    The common language runtime throws SystemException.
2)    The ApplicationException is thrown by a user program rather than the runtime.

Read more at msdn about System.Exception here

How to handle exception: Try Catch Block Statement.

When exceptions are thrown, you need to be able to handle them. This is done by implementing a try/catch block. Code that could throw an exception is put in the try block an exception handling code goes in the catch block

Role of CLR: The common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.

Here is an example of try catch statement:

int[] array1 = {0, 0};
int[] array2 = {0, 0};
try
{
            Array.Copy(array1, array2, -1);
}
catch (ArgumentOutOfRangeException e)
{
            Console.WriteLine("Error: {0}", e);
}

So now we will explore step by step the different way of handling the exception and few important rules to follow,

1: The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully

2: Catch clause can be used without arguments to catch any type of exception, this usage is not recommended.

I.e. for invalid cast exception, use below catches statement

catch (InvalidCastException e) 
{
}

Avoid using below catch statements, although they too will handle esception.

catch (Exception e) 
{
}
catch () 
{
}

Tip: catch those exceptions that you know how to recover from.

3: Using multiple Catch Statements.

We can have multiple catch statement for single Try block. Important point to be kept in mind is the order of the catch, because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.

This is correct

class Demo
{
public static void Main()
{
	int x = 0;
	int y = 0;
try
{
	y = 100/x;
}
catch(DivideByZeroException e)
{
	
}
catch(Exception e)
{
	
}

This is incorrect. This will generate a compile time error

class Demo
{
public static void Main()
{
	int x = 0;
	int y = 0;
try
{
	y = 100/x;
}
catch(Exception e)
{
	Console.WriteLine("Exception" );
}
catch(DivideByZeroException e)
{
}

Here last catch statement DivideByZeroException will never reach.

4#: Throwing Exception Explicitly

If we want to explicitly throw any exception from Try block, we can do it like this;

try 
{
	throw new DivideByZeroException("Invalid Division");
}
catch(DivideByZeroException e)
{
}

5#: Re-throwing an Exception from catch.

A throw statement can be used in a catch block to re-throw the exception that is caught by the catch statement. Sometime we need to extract information from the exception and throw back to parent method.

class demo
{
public void dividebyzero()
{
try
{
	int x = 0;
	int y = 100/x;
}
catch(DivideByZeroException e)
{
	throw; // the control goes back to parent method , from where it was called and get handled 	          //	in the catch statement  written there.
}
}
}

class client
{
public static void Main()
{
	demo object = new demo();
try
{
	object. dividebyzero();
}
catch(DivideByZeroException e)
{
	Console.WriteLine("Exception actually get caught here" );
}
	
}
}

6#: Re-Throw exception based on condition

At time we need to check the conditions and then re-throw exceptions as per requirement.

catch (InvalidCastException e)
{
    if (e.Data == null)
    {
        throw;
    }
    else
    {
        // Take some action.
    }
 }

7#: User defined exceptions:

In .NET we can create our own exception class, but it has to be inherited from exception base class or one of its standard derived classes.

public class EmployeeNotFoundException: Exception
{
    public EmployeeNotFoundException ()
    {
    }

    public EmployeeNotFoundException (string message)
        : base(message)
    {
    }

}
 class demo
{
public static void Main()
{
try
{
	throw new EmployeeNotFoundException();
	throw new EmployeeNotFoundException (“Vishal Nayan”);
}
catch(Exception e)
{
	Console.WriteLine("Exception caught here" + e.ToString());
}
}
}

8#: Finally Block

An exception terminates application and put it into an inconsistent state by not releasing resources or doing some other type of cleanup. A catch block is a good place to figure out what may have gone wrong and try to recover, however it can't account for all scenarios. Finally block does the needful.

For example below, we need to make sure the file which are opened using file stream , should also be closed after the processing has been done on them, so closure of these files can be written in finally block. Finally blocks are always executed, but it is not required.

class demo
{
    static void Main(string[] args)
    {
        FileStream outStream = null;
        FileStream inStream = null;

        try
        {
            outStream = File.OpenWrite("filenumber1.txt");
            inStream = File.OpenRead("filenumber2.txt");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            if (outStream != null)
            {
                outStream.Close();
                Console.WriteLine("outStream closed.");
            }
            if (inStream != null)
            {
                inStream.Close();
                Console.WriteLine("inStream closed.");
            }
        }
    }
}

Finally block can be used for some resource cleanup, like above, , must always be executed even if an exception is thrown. To accomplish this, you can use a finally block. A finally block is always executed, regardless of whether an exception is thrown.

References

Sample Project Source

Download source files -9 kb

 
Sign Up to vote for this article
 
About Author
 
Vishal Nayan
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date -02 Apr 2011
Home Page-
Blog Page-http://vishalnayan.wordpress.com
Vishal is a seasoned professional with hand on experience on Microsoft technologies. He always look for challenging assignment that allows him to learn newer technologies while utilizing his experience of project development and software engineering ethics. In spare time vishal can be found reading business and political personalities, acts as critics at columnist , writing poetries, bird watching , singing ,cooking. He have strong interests in Indian business and political arena and want to be an active one someday. He is also a part-time trainer on framework , WCF and Silverlight. reach him at vishalnayan@gmail.com
 
 
Other popularSectionarticles
Comments
By:Jalpesh VadgamaDate Of Posted:5/3/2011 7:21:29 AM
Jalpesh Vadgama
Catch(Exception ex) { } If you put above block then it will also generate warning. Instead of this You have to do like following Catch(Exception) { }
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top