Saturday 16 February 2013

Posted by Prasad KM | 04:31 Categories:
Exception Handling

1. What is the meaning of Exception ?

Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors.

The C# language's exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running. Exception handling uses the try, catch, and finally keywords to try actions that may not succeed, to handle failures when you decide that it is reasonable to do so, and to clean up resources afterward. Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third-party libraries, or by application code. Exceptions are created by using the throw keyword.

In many cases, an exception may be thrown not by a method that your code has called directly, but by another method further down in the call stack. When this happens, the CLR will unwind the stack, looking for a method with a catch block for the specific exception type, and it will execute the first such catch block that if finds. If it finds no appropriate catch block anywhere in the call stack, it will terminate the process and display a message to the user.

 Example
using System;

class Program
{
    static void Main()
    {
 try
 {
     int value = 1 / int.Parse("0");
     Console.WriteLine(value);
 }
 catch (Exception ex)
 {
     Console.WriteLine(ex.Message);
 }
    }
}

Output

Attempted to divide by zero.
 
 
The following exception types are used widely throughout the CLR and 
.NET Framework. You can throw these yourself or use them as base classes
 for deriving custom exception types.

2. Types of Exception ?

 A. System.ArgumentException

Thrown when a function is called with a bogus argument. This generally indicates a program bug.
 
static void Main() 
    {
        // ArgumentException is not thrown because 10 is an even number.
        Console.WriteLine("10 divided by 2 is {0}", DivideByTwo(10));
        try 
        {
             // ArgumentException is thrown because 7 is not an even number.
             Console.WriteLine("7 divided by 2 is {0}", DivideByTwo(7));
        }
        catch (ArgumentException)
        {
            // Show the user that 7 cannot be divided by 2.
            Console.WriteLine("7 is not divided by 2 integrally.");
        }
    }

    static int DivideByTwo(int num) 
    {
        // If num is an odd number, throw an ArgumentException. 
        if ((num & 1) == 1)
            throw new ArgumentException("Number must be even", "num");

        // num is even, return half of its value. 
        return num / 2;
    } 
 

B. System.ArgumentNullException

Subclass of ArgumentException that’s thrown when a function argument is (unexpectedly) null.

ArgumentNullException is thrown when a method is invoked and at least one of the passed arguments is null but should never be null.
ArgumentNullException behaves identically to ArgumentException. It is provided so that application code can differentiate between exceptions caused by null arguments and exceptions caused by arguments that are not null. For errors caused by arguments that are not null, see ArgumentOutOfRangeException.
ArgumentNullException uses the HRESULT E_POINTER, which has the value 0x80004003.
For a list of initial property values for an instance of ArgumentNullException, see the ArgumentNullException constructors.
C. System.ArgumentOutOfRangeException

Subclass of ArgumentException that’s thrown when a (usually
 numeric) argument is too big or too small. For example, this is thrown 
when passing a negative number into a function that accepts only 
positive values.

using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Guest guest1 = new Guest("Ben", "Miller", 17);
            Console.WriteLine(guest1.GuestInfo());
        }
        catch (ArgumentOutOfRangeException outOfRange)
        {

            Console.WriteLine("Error: {0}", outOfRange.Message);
        }
    }
}

class Guest
{
    private string FirstName;
    private string LastName;
    private int Age;

    public Guest(string fName, string lName, int age)
    {
        FirstName = fName;
        LastName = lName;
        if (age < 21)
            throw new ArgumentOutOfRangeException("age","All guests must be 21-years-old or older.");
        else
            Age = age;
    }

    public string GuestInfo()
    {
        string gInfo = FirstName + " " + LastName + ", " + Age.ToString();
        return(gInfo);
    }

D. System.InvalidOperationException

Thrown when the state of an object is unsuitable for a method to 
successfully execute, regardless of any particular argument values. 
Examples include reading an unopened file or getting the next element 
from an enumerator where the underlying list has been modified partway 
through the iteration.



E. System.NotSupportedException

Thrown to indicate that a particular functionality is not supported. A good example is calling the Add method on a collection for which IsReadOnly returns true.

There are methods that are not supported in the base class, with the expectation that these methods will be implemented in the derived classes instead. The derived class might implement only a subset of the methods from the base class, and throw NotSupportedException for the unsupported methods.
NotSupportedException is also thrown by System.IO classes whenever there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.
NotSupportedException uses the HRESULT COR_E_NOTSUPPORTED, which has the value 0x80131515.


For a list of initial property values for an instance of NotSupportedException, see the NotSupportedException constructors.
 
 
 F. System.NotImplementedException

Thrown to indicate that a function has not yet been implemented.


static void Main(string[] args)
{
    try
    {
        FutureFeature();
    }
    catch (NotImplementedException notImp)
    {
        Console.WriteLine(notImp.Message);
    }
}

static void FutureFeature()
{
    // Not developed yet. 
    throw new NotImplementedException();
}
 
 
 G. System.ObjectDisposedException

Thrown when the object upon which the function is called has been disposed. 

using System;
using System.IO;

public class ObjectDisposedExceptionTest 
{
   public static void Main()
   {     
      MemoryStream ms = new MemoryStream(16);
      ms.Close();
      try 
      {
         ms.ReadByte();
      } 
      catch (ObjectDisposedException e) 
      {
         Console.WriteLine("Caught: {0}", e.Message);
      }
   }
}

0 comments:

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube