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

- 11-05-2009, 11:58 PMmmarkymException class
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 - 11-06-2009, 01:35 AMtravishein
for #3, there is the NumberFormatException. this is automatically thrown from the Integer, Double object wrappers for int, double

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)

}

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);

- 11-06-2009, 01:58 AMSinging Boyo