Sunday, October 2, 2016

Java Exceptions.


Exception Basics

Order of Catch Matters
userChoice = 0; //initialize it
    try {
        userChoice = getInput(inputReader); 
    }// order of catch is important

    catch (NullPointerException e) { 
        System.out.println("Message:"+e.getMessage());
    }
    catch (MyOutOfRangeException e) {
        System.out.println("Message: " + e.getMessage()); 
    }
    catch (Exception e) {
        System.out.println("Catch all Exception"); 
    }

    finally { //always exectued with our without catch
        if (userChoice==0) //still has initial value
            System.out.println("Please try again ..."); 
        else
            System.out.println("Your choice is:"+ userChoice); 
    }
 

Prevent Exceptions As Possible
// Get valid numeric format
public static double getDouble(Scanner sc, String prompt) {
          double d = 0.0;
          boolean isValid = false;
          while (isValid == false)
          {
              System.out.print(prompt);
              if (sc.hasNextDouble())
              {
                  d = sc.nextDouble();
                  isValid = true;
              }
              else {
                  System.out.println(
                      "Error! Invalid number. Try again.");
              }
              sc.nextLine(); // discard any other data
           }
           return d; 
}

// Get valid numeric format
public static double getDoubleWithin (
        Scanner sc,
        String prompt,
        double min, double max )
{
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false) {
        d = getDouble(sc, prompt);
        if (d <= min) {
            System.out.println(
                "Error! Number must be greater than " + 
                min + ".");
        }
        else if (d >= max){
            System.out.println(
                "Error! Number must be less than " +
                max + ".");
        } 
        else
            isValid = true;
    }
    return d; 
}

Scanner sc = new Scanner(System.in);
double subtotal1 = getDouble(sc, "Enter subtotal: "); 
double subtotal2 = getDoubleWithinRange(
                              sc,
                             "Enter subtotal: ",
                             0,
                             10000);


No comments:

Post a Comment