Thursday, October 13, 2011

Exception Handling

Exception Handling

try
{
  - stmts which will cause a exception
  - stmts which will not be executed when exception occurs
}

catch (<exception><var>)
{
   - stmts which should be executed only when an exception occurs
}

Multiple Catch Blocks

when we enclosed the code under try and catch blocks, the execution of the program will be as following:
  • If all the statement in try is executed successfully without executing the catch block from the last stmt of try the control directly jumps to the stmt which is present after catch blocks.
  • If any of the stmt in try comes rises or causes an exception from that line of code without executing any stmts in try control jumps to catch block searching for a matching catch block. If a matching catch block is avilabel executes the stmts under that catch block and than jumps to the stmt after all the catch blocks, if the matching catch block is not avilabel abnormal termination occurs again. 
 - Add a class ExcepDemo.cs and write the following
    class ExcepDemo
    {
        static void Main()
        {
            int x, y, z;
            try
            {
                Console.Write("enter x value : ");
                x = int.Parse(Console.ReadLine());
                Console.Write("enter y value : ");
                y = int.Parse(Console.ReadLine());
                z = x / y;
                Console.WriteLine(z);
            }

            catch (DivideByZeroException ex1)
            {
                Console.WriteLine(" Divisor can't be zero");
            }
            catch (FormatException  ex2)
            {
                Console.WriteLine("Input must be integer");
            }
            catch (Exception ex3)
            {
                Console.WriteLine(" error occurred ");
            }
            Console.WriteLine("end of program");
            Console.ReadLine();
        }
    };
}

Finally Block

(V. imp):- in a block of code which gets executed both the times when an exception occur or did not occur also.
using System;
namespace oopsProject
{
    class FinDemo
    {
        static void Main()
        {
            int x, y, z;
            try
            {
                Console.Write("enter x value : ");
                x = int.Parse(Console.ReadLine());
                Console.Write("enter y value : ");
                y = int.Parse(Console.ReadLine());
                if (y == 1)
                    return;
                z = x / y;
                Console.WriteLine(z);
            }


            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.WriteLine("finally block");
            }
            Console.WriteLine("end of program");
            Console.ReadLine();
        }
    }
}
- In the above program if at all the value to the deviser is given as 1 the execution of the program stops their because we are using return to jump out of the method but all this happens only after executing finally block, because once the control enters into try without executing finally we cannot stop the program execution.

Note – Massage is a property of the exception class which returns the predefined error massage associated with the currently occur exception.

- Massage is a virtual property of class exception which is overridden under all the child exception classes according to their recurrent, so the reference of the exception class holding object of its child class (Currently occur Exception) was able to access property massage of its child class and display the relevant error massage.

Try catch and finally statement can be used in three different combinations:
  • Try and Catch – in this case abnormal termination of the program stops as we are handling the exception.
  • Try Catch and Finally – Execution will be same as above as well as all the stmts in finally gets executed at any cast.
  • Try and Finally – In this case abnormal termination will not stop because we are not handling the exception using catch, but all the stmts is finally will be executed.

 Exceptions are two types 

  1. System exception.
  2. Application exception.
- An exception which gets raised implicitly on some pre-defined error conditions is a system exception. Eg: Format exception divides by zero exception etc.

- An exception which gets raised explicitly on user defined condition is an application exception can also be called as user defined exception.

Exception and Exception Error:-

Exception and Exception Error

Program may come across two different types of error in it.
  • Compile-Time Error.
  • Run-Time Error.
An error which comes into picture at the time of compilation of the program is a compile time error. This error may come due to syntactical mistakes and moreover these are not dangerous.
An error which comes into picture while execution of a program is going on is referred as a run-time error, which may come into picture due to various reason like-
  1. Wrong implementation of logic.
  2. Wrong input supply to program.
  3. Missing of required resources of an application etc.
These errors are what we call as Exception also.
Whenever a run-time error or exception occurs with a program, the program terminate abnormally without executing the next line of code in the program, even if  that code is no way related with the error occurred and also displayed an error massage telling the reason for abnormal termination.

- As a programmer an exception is a class which is responsible in abnormal termination of the program. Within a program we may be coming across various types of runtimes error, mating with the scenario we have been provided with a separate exception class for each runtime error.
  1. FormaleException
  2. DivideByZeroException
  3. IndexOutOfRangeException
  4. NullReferanceException
  5. SqlException etc. 
- These exception classes are predefined under the system Namespace and each class is responsible for abnormal termination as well as displaying of an error massage related with the error.

- Implementation of Exception classes has been done as following

Exception Handling: - 

As we discussed whenever an exception comes into picture the program terminate abnormally without executing the next lines of code even if the code is no way related with the exception, so if we want to stop the abnormal termination of program and still execute the code which is not related with the exception being occurred we need the make use of exception handballing.


- To handle an exception we must enclosed the code under some spatial block known as try-Catch blocks. 

Indexers , Delegates

Indexers

These are near similar to Properties that are used for providing access to an array outside of the class. Once an Indexer is defined on a class the object of that class will work like an array providing access to the values of array i.e. defined inside it.

- Add a class IndexerDemo.cs and write the following:
using System;
namespace oopsProject
{
    public class IndexerDemo
    {
        //Private array declaretion
        string[] arr;
        public IndexerDemo(int size)
        {
        // initializing array with a size
            arr = new string[size];
        // Assigning the default value to array
            for (int i = 0; i < size; i++)
                arr[i] = "empty";
        }
        // defining an indexer to access the array out of the class

        public string this[int index]
        {
            get { return arr[index]; }
            set { arr[index] = value; }
        }
    }
} 

Add a class TestIndexer.cs and write the following:
using System;
namespace oopsProject
{
    class TestIndexer
    {
       
        static void Main()
        {
            IndexerDemo obj = new IndexerDemo(6);
            for (int i = 0; i < 6; i++) ;
            Console.Write(obj[i] +" ");
            Console.WriteLine();
            obj[1] = "red"; obj[3] = "blue"; obj[5] = "green";
            for (int i = 0; i < 6; i++) ;
            Console.Write( obj[i] + " ");
            Console.ReadLine();
       
        }

        public static int i { get; set; }
    }
} 

Delegates

  • These are similar to function pointers, which are avilabel in our traditional languages like C and C++ which provides an option to invoke a function with them, which will be faster in execution.
  • These function pointers are provided under .net languages in a form of Delegates which can be referred as pointer to the method.
  • Invocation of a method can be done in Two different ways –
                     I.   We can invoke a method directly using object of the class.
                     II.  We can invoke a method without object of a class using a Delegate, which is faster in                  execution when compared with first process.

Note – A Delegate is also a type (Reference type).
Using Delegates: - To use a delegate adopt blow process.

Step 1:
Delegate Declearetion: - Here we need to declare a delegate for invoking the method where IO parameters for the Delegate should matched with IO parameters of Method it has to call.
Syntax – 
[<modifiers>] delegate <void |type> <name> [<param def’s>]


Eg:-
public void Add (int x, int y)
{
Console.WriteLine(x +y);
}
public delegate void AddDel( int x, int y);


Eg:-2
public string SayHello (string name)
{
return “Hello “ + name;
}
public delegate string SayDel(string name);


Step 2:
Creating Object of Delegate: - as a delegate is also a type, to consume it we need to create object of it. While creating the object we need to pass the method as a parameter to its constructor, which we want to call using the delegate.
AddDel ad = new AddDel(Add);
SayDel sd = new SayDel(SayHello);
Step 3:
Invoking the Delegate to Execute the Method: - Now we can call the delegate for any number of times so that the method gets executed, where each delegate uses a separate Stack to execute the method for any number of times.
ad (100,50) ; ad (1046,54) ; ad (237,265) ;
sd (“xxx”); sd (“yyy”); sd (“zzz”);

Note – A delegate can be declared either within a namespace or within a class also.

Add a class DelClass.cs and write the following:
using System;
namespace oopsProject
{
    class DelClass
    {
        public string SayHello(String name)
        {
            return "Hello " + name;

        }
        public delegate string SayDel(string name);
        static void Main()
        {

            DelClass obj = new DelClass();
            SayDel sd = new SayDel(obj.SayHello);
            Console.WriteLine(sd("prabhu"));
            Console.WriteLine(sd("nitya"));
            Console.WriteLine(sd("choure"));
            Console.ReadLine();
        }
    }
} 


Delegetes are of two types

  • Uni-cast or Single-Cast delegates
  • Multi- Cast delegates
- If a delegate is used for invoking only a single method, it is a single cast delegate.
- If we can use a delegate for invoking more than one method also i.e. a multi-cast delegate, but if we want to invoke multiple methods using a single delegate then all the method should have the same io parameters.
 - Add a class MultiDel.cs and write the following
using System;
namespace oopsProject
{
    class MultiDel
    {
        public void Add(int x, int y)
        {
            Console.WriteLine("Add : " + (x + y));
        }
        public void sub(int x, int y)
        {
            Console.WriteLine("sub : " + (x - y));
        }
        public void mul(int x, int y)
        {
            Console.WriteLine("mul : " + (x * y));
        }
        public void div(int x, int y)
        {
            Console.WriteLine("div : " + (x / y));
        }
        static void Main()
        {
            MultiDel obj = new MultiDel();
            Math m = new Math(obj.Add);
            m += obj.sub; m += obj.mul; m += obj.div;
            m(100, 50);
            Console.WriteLine();
            m(1844, 5230);
            Console.WriteLine();
            m -= obj.mul;
            m(1023, 523);
            Console.WriteLine();
            Console.ReadLine();
        }
    }
} 

Note – The advantage with multicast delegate is, a single delegate call will execute all the method that is bound to it at a time.

Enumerated Property


Add a class Customer.cs and write the following code: 
using System;
namespace oopsProject
{

    public enum cities { Bangalore, Hyderabad, Mumbai, Kolkata, NewDelhi, Chennai };
    public class Customer
    {
        int _custid;
        string _cname, _state;
        double _balance;
        bool _status;
        cities _city;
        public Customer(int _custid)
        {
            this._custid = _custid;


            //Get all other values from DB basing on given ID:
            _cname = "prabhu";
            _balance = 5000;
            _status = false ;
            _city = 0;
            _state = "karnataka";
            Country = "India";
                       
        }
        //Read only Property
        public int Custid
        {
            get { return _custid; }
        }
        //Read write Property
        public string Cname
        {
            get { return _cname; }
            set { _cname = value; }
        }
        //Read write Property
        public bool Status
        {
            get { return _status; }
            set { _status= value; }
        }
        //Read write Property with a condition
        public double Balance
        {
            get
            {
                if
                    (_status)
                    return _balance;
                else return 0;
            }
            set
            {
                if (value >= 500)
                    _balance = value;
            }
            }
            // enumerated property
       
        public cities city
        {
        get{return _city;}
        set{_city = value;}
        }
        // setting scope of property Accessor independently (2.0)
        public string state
        {
            get { return _state;}
            protected set { _state = value;}
        }
        //Automatic Properties 3.0
            public string Country
            {
            get;
            private set;
            }
       
           }
    }


Enumerated PropertyThese are   property which is defined with a list of constants to choose from. to define these type of properties first we need to declare all the constants under a type known as “enum” .An enum is a collection of constants, which should be declared as following.


Syntax – 
[<modifiers>] enum   <name> {<list of values >};


Eg:-

public enum Days {Monday, Tuesday, Wednesday, Thursday, Friday};

If this enum is used as a type for any property we call it as enumerated property.
- Declaring a variable of enum type
Days weekday = 0;
or
Days weekday = Days.Wednesday ;

Now for the variable weekday we can define a property as Following:
public Days weekday
{
get {return weekday;}
set { weekday = value;}

}
 
New Features to Properties:-

   <!--[if !supportLists]-->        <!--[endif]-->In C# 2.0, there are given an option to define a property setting the scope of each property Accessor independently.
Eg: State property we have defined under customer class.
   <!--[if !supportLists]-->        <!--[endif]-->In C# 3.0, we were given with an option automatic properties, which allows us to define a property without any variable declaration for the property, So set and get blocks doesn’t contain any code in them, but it is must to define both get and set blocks.
Eg: Country Property in above customer class.

Consuming the Properties:-
- Add a class TestCustomer.cs and write the following
using System;
namespace oopsProject
{
    class TestCustomer
    {
        static void Main()
        {
            Customer obj = new Customer(101);                                         
            Console.WriteLine(obj.Custid);
            //Assignment i not possible as property is read only
            //obj.Custid = 102;

            Console.WriteLine(obj.Cname);
            obj.Cname = "xyz";
            Console.WriteLine(obj.Cname);

            Console.WriteLine(obj.Status );
            //Balance will be zero here as status is inactive
            Console.WriteLine(obj.Balance);
            obj.Status = true;
            Console.WriteLine(obj.Status);
           
            // now it returns balance as status is active
           
            Console.WriteLine(obj.Balance);
            obj.Balance = 400; //assignment fails
           
            // here as it is less than 500

            obj.Balance = 400;
            Console.WriteLine(obj.Balance);

            // assignment succeeds as it is greater than 500

            obj.Balance = 600;
            Console.WriteLine(obj.Balance);
           
            Console.WriteLine(obj.city);
            obj.city = cities.Hyderabad;
            Console.WriteLine(obj.city);
            Console.WriteLine(obj.state);
            // Assigning value to the property is invalid as current
            //class is not a child class of customer
            //obj.state = "AP";
            Console.WriteLine(obj.Country);
            Console.ReadLine();

        }
    }
} 

Note – Just like we have Abstract method and Virtual method, we can define Property also as abstract and virtual. So that we can override them under Child class.