Friday, June 5, 2015

Exception Handling In C Sharp

Exception Handing

Exception handling is of 2 types:
  • System-level exceptions
  • Application-level exceptions
System-level exceptions are the exceptions thrown by the system. These exceptions are thrown by the CLR. E.g. exception thrown due to failure in database connection or network connection.

Application-level exceptions are thrown by user-created applications. E.g. exceptions thrown due to arithmetic operations or referencing any null object.

InvalidCastException Class 


using System;
class InvalidCastError
{
    static void Main(string[] args)
    {
        try
        {
            float numOne = 3.14F;
            Object obj = numOne;
            int result = (int)obj;
            Console.WriteLine("Value of numOne = {0}", result);
        }
        catch (InvalidCastException objEx)
        {
            Console.WriteLine("Message : {0} ", objEx.Message);
            Console.WriteLine("Error: {0}", objEx);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}

ArrayTypeMismatchException Class


using System;
class ArrayMisMatch
{
    static void Main(string[] args)
    {
        string[] names = { "James""Jack""Peter" };
        int[] id = { 10, 11, 12 };
        double[] salary = { 1000, 2000, 3000 };
        float[] bonus = new float[3];
        try
        {
            salary.CopyTo(bonus, 0);
        }
        catch (ArrayTypeMismatchException objType)
        {
            Console.WriteLine("Error: {0}", objType);
        }
        catch (Exception objEx)
        {
            Console.WriteLine("Error : {0}", objEx);
        }
    }
}

NullReferenceException Class


using System;
class Employee
{
    private string _empName;
    private int _empID;
    public Employee()
    {
        _empName = "David";
        _empID = 101;
    }
    static void Main(string[] args)
    {
        Employee objEmployee = new Employee();
        Employee objEmp = objEmployee;
        objEmployee = null;
        try
        {
            Console.WriteLine("Employee Name: " + objEmployee._empName);
            Console.WriteLine("Employee ID: " + objEmployee._empID);
        }
        catch (NullReferenceException objNull)
        {
            Console.WriteLine("Error: {0}", objNull);
        }
        catch (Exception objEx)
        {
            Console.WriteLine("Error : {0}", objEx);
        }
    }
}

Public Methods of System.Exception Class


using System;
class ExceptionMethods
{
    static void Main(string[] args)
    {
        byte numOne = 200;
        byte numTwo = 5, result = 0;
        try
        {
            result = checked((byte)(numOne * numTwo));
            Console.WriteLine("Result = {0}", result);
        }
        catch (Exception objEx)
        {
            Console.WriteLine("Error  Description : {0}", objEx.ToString());
            Console.WriteLine("Exception : {0}", objEx.GetType());
        }
    }
}

Public Properties Of System.Exception class


using System;
class ExceptionMethods
{
    static void Main(string[] args)
    {
        byte numOne = 200;
        byte numTwo = 5, result = 0;
        try
        {
            result = checked((byte)(numOne * numTwo));
            Console.WriteLine("Result = {0}", result);
        }
        catch (OverflowException objEx)
        {
            Console.WriteLine("Message : {0}", objEx.Message);
            Console.WriteLine("Source : {0}", objEx.Source);
            Console.WriteLine("TargetSite : {0}", objEx.TargetSite);
            Console.WriteLine("StackTrace : {0}", objEx.StackTrace);
        }
        catch (Exception objEx)
        {
            Console.WriteLine("Error  : {0}", objEx.ToString());
        }
    }
}

Finally Keyword


using System;
class InvalidCastError
{
    static void Main(string[] args)
    {
        try
        {
            float numOne = 3.14F;           
            Console.WriteLine("Value of numOne = {0}", numOne);
        }
        catch (InvalidCastException objEx)
        {
            Console.WriteLine("Message : {0} ", objEx.Message);
            Console.WriteLine("Error: {0}", objEx);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        finally
        {
            Console.WriteLine("End of program");
        }
    }
}

Throw keyword - ArgumentNullException()


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
    class Program
    {
        static void thro(string name)
        {
            if (name == null)
                throw new ArgumentNullException();
            else
           
                Console.WriteLine(name);           
        }
        static void Main(string[] args)
        {
            try
            {
                string name;
                name = null;
                thro(name);
            }
            catch (ArgumentNullException ex)
            {
                System.Console.WriteLine(ex);
            }
        }
    }
}

Nested try catch


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
    class Program
    {       
        static void Main(string[] args)
        {
            string[] names = { "John""James" };
            int numOne = 0;
            int result;
            try
            {
                try
                {
                    result = 133/numOne;
                }
                catch(ArithmeticException ae)
                {
                    System.Console.WriteLine(ae);
                }
                names[2] = "aptech";
            }
            catch(IndexOutOfRangeException ie)
            {
                System.Console.WriteLine();
                System.Console.WriteLine(ie);
            }
        }
    }
}

User defined exception

Example 1
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
    class Program : Exception
    {
        public Program()
        {
            Console.WriteLine("Age should be between 17 and 100");
        }       
    }
    class handleExp
    {
        public static void Main()
        {
            int val;
            val = Int32.Parse(Console.ReadLine());
            try
            {
                if (val < 17 || val > 100)
                {
                    throw new Program();
                }
                else
                {
                    Console.WriteLine("welcome to polling booth");
                }

            }
            catch (Program obj)
            {
                Console.WriteLine(obj.Message);
            }               
        }
    }
}

Example 2

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
    class Program : Exception
    {
        public Program(string msg): base(msg)
        {
            Console.WriteLine("Constructor invoked");
        }
    }
    class handleExp
    {
        public static void Main()
        {
            int value;
            try
            {
                value = Int32.Parse(Console.ReadLine());
                if (value < 10 || value > 100)
                    throw new Program("this exception is going to be thrown by the program");
                else
                    Console.WriteLine(value);

            }
            catch (Program obj)
            {
                Console.WriteLine(obj.Message);
            }
        }
    }
}

Tester-Doer Pattern


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
    class NumberDoer
    {
        public void Process(int numOne, int numTwo)
        {
            try
            {
                if (numTwo == 0)
                {
                    throw new DivideByZeroException("Value of divisor is zero");
                }
                else
                {
                    Console.WriteLine("Quotient: " + (numOne / numTwo));
                    Console.WriteLine("Remainder: " + (numOne % numTwo));
                }
            } catch (DivideByZeroException objDivide)
            {
                Console.WriteLine("Error {0}: " + objDivide);
            }
        }
    }
    class handleExp
    {
        NumberDoer objDoer = new NumberDoer();
        public void AcceptDetails()
        {
            int dividend = 0;
            int divisor = 0;
            Console.WriteLine("Enter the value of dividend");
            try
            {
                dividend = Convert.ToInt32(Console.ReadLine());
            }
            catch (FormatException objForm)
            {
                Console.WriteLine("Error : {0}" + objForm);
            }

            Console.WriteLine("Enter the value of divisor:");

            try
            {
                divisor = Convert.ToInt32(Console.ReadLine());
            }
            catch (FormatException objFormat)
            {
                Console.WriteLine("Error: {0}" + objFormat);
            }

            if ((dividend > 0) || (divisor > 0))
            {
                objDoer.Process(dividend, divisor);
            }
            else
            {
                Console.WriteLine("Invalid Input");
            }
        }
        public static void Main()
        {
            handleExp objTester = new handleExp();
            objTester.AcceptDetails();                     
        }
    }
}

TryParse Pattern


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
    class Product
    {
        private int _quantity;
        private float _price;
        private double _sales;
        string _productName;
        public Product()
        {
            _productName = "Motherboard";
        }
        public void AcceptDetails()
        {
            Console.WriteLine("Enter the number of " + _productName + " sold");
            try
            {
                _quantity = Int32.Parse(Console.ReadLine());
            }
            catch (FormatException objFormat)
            {
                Console.WriteLine("Error {0}: " + objFormat);
                return;
            }
            Console.WriteLine("Enter the price of the product");
            if (float.TryParse((Console.ReadLine()), out _price) == true)
            {
                _sales = _price * _quantity;
            }
            else
            {
                Console.WriteLine("Invalid price inserted");
            }
            Console.WriteLine("Product Name: " + _productName);
            Console.WriteLine("Product Price: " + _price);
            Console.WriteLine("Quantity sold: " + _quantity);
            Console.WriteLine("Total Sale Value: " + _sales);
        }
        static void Main(string[] args)
        {
            Product objGoods = new Product(); objGoods.AcceptDetails();
        }
    }

}

System.TypeInitializationException Class


using System;
class TypeInitError
{
    static TypeInitError()
    {
        throw new ApplicationException("This program throws TypeInitializationException error.");
    }
    static void Main(string[] args)
    {
        try
        {
            TypeInitError objType = new TypeInitError();
        }
        catch (System.TypeInitializationException objEx)
        {
            Console.WriteLine("ERROR: {0}", objEx);
        }
        catch (Exception objEx)
        {
            Console.WriteLine("Error : {0}", objEx);
        }
    }
}

The throw statement


using System;
class RethrowException
{
    static void Main(string[] args)
    {
        string[] customerNames = new string[3];
        int[] age = new int[3];
        try
        {
            try
            {
                for (int i = 0; i < customerNames.Length; i++)
                {
                    Console.WriteLine("Enter the name of the  customer: ");
                    customerNames[i] = Console.ReadLine();
                    Console.Write("Enter the age of the Customer:");
                    age[i] = Convert.ToInt32(Console.ReadLine());
                }
            }
            catch (FormatException objEx)
            {
                Console.WriteLine("Invalid input");
                //throw;
            }
        }
        catch (Exception objEx)
        {
            Console.WriteLine("Error thrown by the inner catch block  caught in the outer catch block");
        }
    }
}

Custom Exception


using System;
class NewCustom : Exception
{
    public NewCustom(string msg) : base(msg)
    {
    }
    static void Main(string[] args)
    {
        int dividend = 133;
        int divisor;
        int result = 0;
        Console.WriteLine("Enter the value of divisor");
        try
        {
            divisor = Convert.ToInt32(Console.ReadLine());
            if (divisor == 0)
            {
                throw new NewCustom("Zero not allowed here");
            }
            if (divisor < 0)
            {
                throw new NewCustom("Please enter a positive number");
            }
            Console.WriteLine("You entered: " + divisor.ToString());
            result = dividend / divisor;
        }
        catch (NewCustom objEx)
        {
            Console.WriteLine("Error :" + objEx.Message);
        }
        Console.WriteLine("Result of division: " + result);
    }

No comments:

Post a Comment