// Walker M. White
// March 11, 2012

import java.io.*;

/** Static methods to demonstrate how exceptions work. */
public class Throwing {
    
    /** 
     * Our first method.  Passes the argument i to secondMethod.  
     *
     * Throws: ArithmeticException   i == 2
     * Throws: IllegalArgumentException i == 3
     * Throws: IOEception     i == 4
     * Throws: RuntimeException   i == 5
     */
    public static void firstMethod(int i) throws IOException {
        System.out.println("Starting first method.");
        
        secondMethod(i);
        
        System.out.println("Ending first method");
        
        return;
    }
    
    /** 
     * Our second method.  Passes the argument i to throwException.  
     * It contains the try-catch block for IllegalArgumentException.
     *
     * Throws: ArithmeticException   i == 2
     * Throws: IllegalArgumentException i == 3
     * Throws: IOEception     i == 4
     * Throws: RuntimeException   i == 5
     */
    public static void secondMethod(int i) throws IOException {
        System.out.println("Starting second method.");
        
        throwException(i);
        
        System.out.println("Ending second method.");
        return;
    }
    
    /** 
     * This function does nothing but throw exceptions.
     * The Exception thrown depends on i.  Does nothing
     * if i is 1.
     * Throws: ArithmeticException   i == 2
     * Throws: IllegalArgumentException i == 3
     * Throws: IOEception     i == 4
     * Throws: RuntimeException   i == 5
     */
    public static void throwException(int i) throws IOException {
        System.out.println("Starting third method.");
        
        if (i == 1) {
            // Do nothing.
        }
        
        if (i == 2) {
            // This exception is for bad arithmetic (i.e. divide by zero)
            //int x = 1/0;
            throw new ArithmeticException("My error message");
        } 
        
        if (i == 3) {
            // This exception is if the parameters are bad (i.e. not positive number).
            throw new IllegalArgumentException();
        } 
        
        if (i == 4) {
            // For IO exceptions.  You will never use this.
            throw new IOException();
        } 
        
        if (i == 5) {
            // This is a generic exception if nothing else is appropriate.
            // Though, you should make your own exception in such a case.
            throw new RuntimeException();
        }
        
        System.out.println("Ending third method");
    }
}
