samedi 10 octobre 2020

Is it possible to throw an exception from a try block in java?

I have an assignment that I'm working on and we are told to answer the question using Exception handling. Here's the question:

The validateShelveNo(String) method receives the shelve number and check whether the shelveNo starts with ABC. If not then the method throws exception error ”The shelve number must start with ABC ”. Also the method checks whether the barcode ends with any numeric value from 101 to 120 , otherwise the method throws “The shelve number must be within 101 and 120”. When the shelve number met all requirements the method must return true.

and my answer:

public boolean validateShelveNo(String shelveNo) {
    boolean test2 = true;
   
        if (shelveNo.startsWith("ABC") == true)) {
            test2 = true;
        }
    else
      {
         throw new Exception("The shelf number must start with ABC ");
        test2 = false;
      }
  
        String lastThreeDigits = "";
        if (shelveNo.length() > 3)
 {
            lastThreeDigits = shelveNo.substring(shelveNo.length() - 3);
            for (int i = 0; i < lastThreeDigits.length; i++) {
                if ((Character.isDigit(lastThreeDigits.charAt(i)) == true)) {
                    int digits = Integer.parseInt(lastThreeDigits);
                    if (digits >= 101 && digits <= 120) {
                        test2 = true;
                    }
                    else {
                        throw new IllegalArgumentException("The shelf number must be within 101 and 120");
                        test2 = false;
                    }
                    test2 = true;
                }
                else {
                    System.out.println(" The last 3 Characters are not numeric");
                    test2 = false;
                }
            }
        }
        else {
            throw new IllegalArgumentException("shelf number has less than 3 characters!");
            test2 = false;
        }
    }
   
    return test2;
}

Aucun commentaire:

Enregistrer un commentaire