10. Exceptions

An exception is an errror that occurs during the execution of a program.

//The general form try-catch-finally   
try 
{  
}
catch(Exception  exception) 
{   
}
finally  
{ 
}

try cattch finally

        public void MultipleCatchApp()
        {
            try
            {
                int a = 10;
                int b = 0;
                int result = x/y; //error: divide by zero	
                Console.WriteLine("Result = {0}" , result);
            }
    
            catch(DivideByZeroException ex)
            {
                Console.WriteLine("Exception occurred due to divide by zero");
            }
            catch(Exception ex)
            {
                Console.WriteLine(“Exception block”);
            }
            finally
            {
               Console.WriteLine("finally block");
            }
        }
        

throw

         public void ThrowTest()
         {
            int a =10;
            int b = 0;
            try
            {
                if(b == 0)
                throw new DivideByZeroException("Invalid Division");
            }
            catch(DivideByZeroException ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            catch(Exception ex)
            {
                Console.WriteLine("Exception block");
            }
            finally
            {
                Console.WriteLine("finally block");
            }
        }
        

Excepion Types

Exception types Exception are of two types: (1) Standard Exceptions and

ii) User Defined Exceptions or Custom Exceptions.


Standard Exceptions
            Standard Exceptions
            System.OutOfMemoryException 
            System.NullReferenceException 
            Syste.InvalidCastException 
            Syste.ArrayTypeMismatchException 
            System.IndexOutOfRangeException	
            System.ArithmeticException 
            System.DevideByZeroException 
            System.OverFlowException 
        

Standard Exceptions

User-defined Exceptions are also known as Custom Exceptions, inherit from eigther Exception class or one of the above Standard derived classes.

        using System;
        namespace QSSTraining
        {
            class MyCustomException : Exception
            {
                public MyCustomException(string message)
                {
                    Console.WriteLine(message);
                }
            }
            class Program
            {
                public static void Main()
                {
                    try
                    {
                        throw new MyCustomException("User Defined Exception");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception : " + ex.Message.ToString());
                    }
                    Console.Read();
                }
            }
        }