I'm writing a program that adds, subtracts, multiplies, and divides. What exception classes are there that would account for 1) negative numbers 2) operations by zero 3) entering letters in place of numbers.
mark
Printable View
I'm writing a program that adds, subtracts, multiplies, and divides. What exception classes are there that would account for 1) negative numbers 2) operations by zero 3) entering letters in place of numbers.
mark
for #3, there is the NumberFormatException. this is automatically thrown from the Integer, Double object wrappers for int, double
2. there isn't usually an exceptions when operations by zero, here I assume you mean divide by zero.Code:String strNumber = "12345sdgf";
try {
double aDouble = Double.parseDouble(strNumber);
}
catch (NumberFormatException ex) {
// the user entered something that was not parseable into a number (e.g. letters)
}
what is displayed is "result: infinity"Code:double numerator = 4;
double denominator = 0;
double quotient = numerator / denominator;
System.out.println("result: " + quotient);
A good general exception that I like to use for general validation of what my program expects, like my business rules, is the IllegalArgumentException. It extends RuntimeException, so that means you don't have to explicitly wrap things into a try/catch all the time.
for example, back to this divide example, i now hande a check for negative numbers, and divide by zero
Code:double numerator = -5;
double denominator = 0;
if (numerator < 0) {
throw new IllegalArgumentException("numerator cannot be less than zero: " + numerator);
}
if (denominator <= 0) {
throw new IllegalArgumentException("denominator cannot be negative or zero: " + denominator);
}
// in this example, because of the checking above, we would not get here, exception would be thrown instead.
double quotient = numerator / denominator;
System.out.println("result: " + quotient);