Reading material

Pages 214-218 (Section 5.5 and 5.6) and pages 228-236 (Section 6.1)

Additional material

InspectableTree
Tree

Question

Assume the nodes of tree t contain integers. Let n be a node of tree t. Compute the sum of the integers stored in the nodes of the subtree of tree t rooted at node n.

Algorithm sum(t, n):
   Input: tree whose nodes contains integers and a node of the tree
   Output: sum of the integers stored in the nodes of the subtree of tree t rooted at node n

Exceptions

Additional material about exceptions can be found here.

Fibonacci
ExceptionScope
Propagation

Catching exceptions

public static void fibonacci(String[] args)
{
       try
       {

              int lo = 1;
              int hi = 1;
              int n = Integer.parseInt(args[0]);
              System.out.println(lo);
              for (int i = 1; i < n; i++)
              {
                    System.out.println(hi);
                    int temp = hi;
                    hi = lo + hi;
                    lo = temp;
              }
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
              System.err.println("No command line argument provided");
        }
        catch (NumberFormatException e)
        {
              System.err.println("Command line argument " + e.getMessage() + " is not an integer");
        }
        finally
        {
              System.out.println("Done!");
        }

}

Specifying exceptions

public static void fibonacci(String[] args) throws ArrayIndexOutOfBoundsException, NumberFormatException
{
       int lo = 1;
       int hi = 1;
       int n = Integer.parseInt(args[0]);
       System.out.println(lo);
       for (int i = 1; i < n; i++)
       {
             System.out.println(hi);
             int temp = hi;
             hi = lo + hi;
             lo = temp;
       }
}

Throwing exceptions

public static void fibonacci(String[] args) throws ArrayIndexOutOfBoundsException, NumberFormatException
{
       int lo = 1;
       int hi = 1;
       if (args.length == 0)
       {
             throw new ArrayIndexOutOfBoundsException();
       }
       int n = Integer.parseInt(args[0]);     // may still throw a NumberFormatException
       System.out.println(lo);
       for (int i = 1; i < n; i++)
       {
             System.out.println(hi);
             int temp = hi;
             hi = lo + hi;
             lo = temp;
       }
}