Create your own exception class based on Exception : Custom Exception : Language Basics C# Examples


C# Examples » Language Basics » Custom Exception »

 

Create your own exception class based on Exception









    
using  System;
using  System.Collections;

public  class  MyException  :  Exception
{
        public  MyException(  String  reason,  Exception  inner  )  :base(  reason,  inner  )  {
        }
}

public  class  MainClass
{
        static  void  Main()  {
                try  {
                        try  {
                                ArrayList  list  =  new  ArrayList();
                                list.Add(  1  );

                                Console.WriteLine(  "Item  10  =  {0}",  list[10]  );
                        }
                        catch(  ArgumentOutOfRangeException  x  )  {
                                throw  new  MyException(  "I'd  rather  throw  this",x  )  ;
                        }
                        finally  {
                                Console.WriteLine(  "Cleaning  up..."  );
                        }
                }
                catch(  Exception  x  )  {
                        Console.WriteLine(  x  );
                        Console.WriteLine(  "Done"  );
                }
        }
}
    
   
  
   



Output

Cleaning up...
MyException: I'd rather throw this ---> System.ArgumentOutOfRangeException: Index was out of range.
Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.Collections.ArrayList.get_Item(Int32 index)
   at MainClass.Main()
   --- End of inner exception stack trace ---
   at MainClass.Main()
Done


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Language Basics
» Custom Exception