/**
 * example of throwing and catching Exceptions
 *
 * Example of entries that would cause exceptions:
 *      java  Except1use          --> Missing arguments 
 *      java  Except1use  AA   3  --> Argument not a number
 *      java  Except1use  10  -2  --> Cannot calculate average - count <= 0
 */

public class Except1
{
    public static void main(String[ ] args)
    {
        
        //---- Check for entry of at least 2 arguments (total and count) ----------

        //in this try block, we check to make sure that client entered 2 arguments. 
        //If not, we throw an Exception    

        try {
            if (args.length != 2)               //this is the same as: 
                throw new Exception();          //Exception x = new Exception(); 
        }                                       //throw x;
        catch (Exception e) {
            System.out.println("Missing args - Re-enter with total and count");
            System.exit(0);
        }

        double avg = calcAvg(args);         	//call calcAvg method
                                                //and pass it the args array
        System.out.println("The average is: " + avg);
    }


    static double calcAvg(String[ ] args)
    {  

        //---- Try converting args[0] to double, and args[1] to int ---------------

        //in this try block, an entry of anything other that a double and an integer 
        //will cause Java to automatically throw and Exception.
        //Notice that we do not throw the exception here, Java does.

        double total = 0;
        int    count = 0;

        try {
            total =  Double.parseDouble(args[0]);   //convert String to double
            count =  Integer.parseInt(args[1]);     //convert String to int 
        } 
        catch (Exception e) {
            System.out.println("Argument supplied is not a valid number");  //my message
            System.out.println(e);                      //Java's message
            System.exit(0);
        }
                                        

        //---- Try calculating an average ------------------------------------------

        //in this try block, if the denominator is <= 0  
        //we throw an Exception("with a message")
        //The message is printed using e.toString( ) or simply e

        try {
            if (count <= 0)
                throw new Exception("count less than or equal to 0");
            else 
                return(total / count);
        }
        catch (Exception e) {
            System.out.println("Cannot calculate average \n" + e.getMessage() );
            return(0);
        }
    }
}