Tuesday, 24 January 2012

Learning exception handling in C# with 8 Points

Learning exception handling in C# with 8 Points

Learning exception handling in C# with 8 Points

Exceptions: 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.
Exceptions are nothing but objects of the type Exception.


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 exception.
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.
Reference: http://msdn.microsoft.com/en-us/library/0yd65esw.aspx

Cheers

Posted by February 27, 2011 

No comments :