Use a nested try block. : Try Catch : Language Basics C# Examples


C# Examples » Language Basics » Try Catch »

 

Use a nested try block.









    
using  System;  
  
class  MainClass  {  
    public  static  void  Main()  {  
        int[]  numer  =  {  4,  8,  16,  32,  64,  128,  256,  512  };  
        int  d  =  0;
  
        try  {  //  outer  try  
            for(int  i=0;  i  <  10;  i++)  {  
                try  {  //  nested  try  
                    Console.WriteLine(numer[i]  +  "  /  "  +  
                                                          numer[i]  +  "  is  "  +  
                                                          numer[i]/d);  
                }  
                catch  (DivideByZeroException)  {  
                    //  catch  the  exception  
                    Console.WriteLine("Can't  divide  by  Zero!");  
                }  
            }  
        }    
        catch  (IndexOutOfRangeException)  {  
            //  catch  the  exception  
            Console.WriteLine("No  matching  element  found.");  
            Console.WriteLine("Fatal  error  --  program  terminated.");  
        }  
    }  
}
    
   
  
   



Output

Can't divide by Zero!
Can't divide by Zero!
Can't divide by Zero!
Can't divide by Zero!
Can't divide by Zero!
Can't divide by Zero!
Can't divide by Zero!
Can't divide by Zero!
No matching element found.
Fatal error -- program terminated.


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Language Basics
» Try Catch