class CallStackExampleWithCustomException3
{
   public static void main(String[] args)
   {
      try
      {
            Hazard myHazard = new Hazard();
            System.out.println("2nd line of try block in main");
            myHazard.methodC();
            System.out.println(16 / 0);
      }
      catch(Exception exc)
      {
         System.out.println("caught an exception");
         exc.printStackTrace();
         System.out.println("This application needs to close immediately - sounds nicer than a silent crash.");
       }
       finally
       {
         System.out.println("Finally block: Do something whether or not an exception is thrown, such as close a network connection.");
       }
   }
}

class MyCustomException extends Exception
{
   MyCustomException() throws MyCustomException
   {
      System.out.println("constructor of MyCustomException");
   }
}

class Hazard
{
   Hazard()
   {
      System.out.println("Constructor of Hazard");
   }

   void methodA()
   {
      System.out.println("in method A");
   }
   
   void methodB()
    {
         System.out.println("in method B");
         methodA(); // which calls methodB
    }
   
   void methodC() throws MyCustomException
   {
      System.out.println("in method C");
      methodB(); // which calls methodA
      int[] myIntArray = {0, 1, 2, 3};
      for(int i = 0; i <= myIntArray.length; i++)
      {
         // reference an element that does not exist in the array
         System.out.println("The current value of i is: " + myIntArray[i]);
         /* The following two lines do not execute
         * if an exception occurs because it
         * forces the JVM to immediately execute the catch block: */

         if(i == 3)
         {
            throw new MyCustomException();
         }
      }
   }
}


// note: another throws example is at http://write-technical.com/126581/session8/index.htm#Declaring%20that%20a%20method%20throws%20exceptions
