Breaking News

Tuesday 1 October 2013

EXCEPTION HANDLING

objectives :
  • understanding exception handling
  • the try....catch....finally statement
  • the throw statement 
  • checked and unchecked statements
Exception handling:

Exception  is a runtime error that arises because of some abnormal condition , such as division a number by zero , passing a string to a variable that hold an integer value. capturing and handling a runtime error is one of the important task for any programmer; before discussing the runtime error , lets take a look at compile time error. 

Compile time error are those error that occur during compilation of a program. it can happen due to bad coding and incorrect syntax. you can correct these error after looking at the error message that the compiler generates. one the other hand ,
  
  Runtime error are those errors that occur during the execution of the program and therefore , at that time they cannot be corrected.




To do so , you should first identify the following two aspects:

  1. Find out those parts of a program which can causes runtime error.
  2. How to handle those errors , when they occur.

describes some common Exception classes:

  1. SystemException  >>  Represent a base class for other exception classes.
  2. AccessException  >>  occurs when a type member , such as a variable , can not be accessed.
  3. ArgumentException  >>  defines a invalid argument to a method.
  4. ArgumentNullException  >>  occurs if an null argument passes to a method that does not accept it.
  5. ArgumentOutOfRangeException  >> occurs if a argument value is not within range.
  6. ArithmeticException  >>  occurs if arithmetic overflow or underflow has occurred etc...
In C# , exceptions can be handled by using the following two statements:

  • The try....catch....finally statement
  • The throw statement

let's discuss these points in details :

The try....catch,,,,finally Statement :

C# provides three keywords for exception handling -- try , catch , and finally. the try blocks enclosed those statement that can causes exception , whereas the catch block enclosed the statement to handle the exception , if it occurs. the statement enclosed in the finally blocks are always executed , weather an exception occur or not.

multiple catch blocks exist for a single try block. all these catch blocks are used to handle different type of exceptions that are raised inside the try block. there can be only one finally block for a try block.

the following code shows the use of the try...catch...finally statement :

try
 {
   div = 100/ number;
 }
catch(DevideByZeroException de)
 {
   Console.WriteLine(" exception occurred);
 }
finally
 {
   Console.WriteLine("result is : "+div);
 Console.ReadKey();
}

In the preceding code , when the statement inside the try block execute  the control may transfer to the catch block depending upon the value of the number variable is 0 , then DevideByZeroException raised and program control transfer to the catch block and executed the statement inside the catch block and after that the statement executed inside the finally block. is the value of number variable is another than 0 then the control is not transferred to the catch block and then directly transferred to the finally block and executed the inside the statement of finally block.

showing the code of MyException Application :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace try_and_catch_and_finally_blocks.cs
{
    class Program
    {
      static  int res;
      public static void dividingnumbers(int a, int b)
      {
          try
          {
              res = a / b;
              Console.WriteLine(res);
          }
          catch (DivideByZeroException e)
          {
              Console.WriteLine("exception caught.." + e);
          }
          finally
          {
              Console.WriteLine("result is :" + res);
          }
          Console.WriteLine("after handling the exception..");
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            dividingnumbers(10,0);
            Console.ReadKey();
        }
    }
}

output :



NOTE :

If any exception occurs in the try block , the program control directly transfer to its respective catch block and later on the finally block. In C# catch and finally blocks are not compulsory. In a program , a try block contain one and more catch blocks , only a finally blocks or both catch and finally blocks. If no exception occurs inside the try block , the program control is transferred to the finally block.






The throw statement:

the throw statement is used to raise an exception in case an error occur in a program. the throw statement takes only a single argument to throw the exception. when a throw statement is encountered , a program terminates. In C# , it is possible to throw an exception programmatically.
you can use the throw keyword to throw an exception.

the following code shows an example of the throw statement :

try
 {
   throw new DivideByZeroException();
 }
catch(DivideByZeroException e)
  {
     Console.WriteLine("Exception");
  }

in the preceding code you can see that we have throw a new DivideByZeroException explicitly.

showing the code of MyThrowException :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace the_throw_statement.cs
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            Console.WriteLine("enter a number");
            number = Convert.ToInt32(Console.ReadLine());
            try
            {
                if (number > 10)
                {
                    throw new Exception("out of size");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("exception has been occurd\n"+e.Message);
            }
            finally
            {
                Console.WriteLine("this is the last statement ");
                Console.ReadKey();
            }
        
        }
    }

    }

output :















Checked and Unchecked Statement :

Checked and Unchecked statements are used to check the memory overflow exceptions. the Check keyword is used to check the overflow for integral-type arithmetic operations and conversions. Overflow occurs when the value of a variable is exceeds required the original length of the variable.
the Unchecked keyword ignores the overflow checking of the integral type arithmetic operations and conversions.

showing the code of the CheckOverflow Application :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace check_and_uncheck_statement.cs
{
    class Program
    {
        static void Main(string[] args)
        {
            byte number1, number2, result;
            number1 = 123;
            number2 = 123;
            try
            {
                result = unchecked((byte)(number1 * number2));
                Console.WriteLine("unchecked result :" + result);


                result = checked((byte)(number1 * number2));
                Console.WriteLine("checked result :" + result);
                {
                    throw new Exception("out of size");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("System.OverflowException: Arithmetic operation resulted in an overflow."+e.Message);
            }
            finally
            {
                Console.WriteLine("\n press enter to exit..");
                Console.ReadKey();
            }
        }
    }
}


output :




Read more ...
© 2013 Post by repter_x