Throwing Exceptions
File Factorials.java contains a program that calls the factorial method of the MathUtils class to compute the
factorials of integers entered by the user. Save these files to your directory and study the code in both, then
compile and run Factorials to see how it works. Try several positive integers, then try a negative number. You
should find that it works for small positive integers (values < 17), but that it returns a large negative value for
larger integers and that it always returns 1 for negative integers.
1. Returning 1 as the factorial of any negative integer is not correct—mathematically, the factorial function is not
defined for negative integers. To correct this, you could modify your factorial method to check if the argument is
negative, but then what? The method must return a value, and even if it prints an error message, whatever value is
2. Returning a negative number for values over 16 also is not correct. The problem is arithmetic overflow—the
factorial is bigger than can be represented by an int. This can also be thought of as an IllegalArgumentException—
this factorial method is only defined for arguments up to 16. Modify your code in factorial to check for an
argument over 16 as well as for a negative argument. You should throw an IllegalArgumentException in either
case, but pass different messages to the constructor so that the problem is clear.
// ****************************************************************
// Factorials.java
//
// Reads integers from the user and prints the factorial of each.
//
String keepGoing = “y”;
Scanner scan = new Scanner(System.in);
while (keepGoing.equals(“y”) || keepGoing.equals(“Y”))
{
System.out.print(“Enter an integer: “);
int val = scan.nextInt();
System.out.println(“Factorial(” + val + “) = “
+ MathUtils.factorial(val));
System.out.print(“Another factorial? (y/n) “);