Question: Handling an ArithmeticException. The following program calls getQuotient, which divides its two passed-in values and returns the quotient as a floating-point number. The program works
Handling an ArithmeticException.
The following program calls getQuotient, which divides its two passed-in values and returns the quotient as a floating-point number.
![import java.util.Scanner; public class Division ByZero { public static void main(String[] args) { Scanner](https://dsd5zvtm8ll6.cloudfront.net/images/question_images/1704/8/8/4/433659e78d162c981704884430078.jpg)
The program works well for the normal cases, but when the user enters 0 for the divisor, the program generates this error:
Exception in thread "main" java.lang.ArithmeticException: / by zero Modify the getQuotient method by putting the division operation in a try block and following it with a catch block that returns either Double.POSTIVE_INFINITY if the dividend is positive or Double.NEGATIVE_INFINITY if the dividend is negative.
import java.util.Scanner; public class Division ByZero { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int dividend, divisor; double quotient; System.out.print("Enter dividend: "); dividend = stdin.nextInt(); System.out.print("Enter divisor: "); divisor = stdIn.nextInt (); quotient Division ByZero.getQuotient (dividend, divisor); = System.out.println( "quotient (" + dividend + "," + divisor + ") -> " + quotient); } // end main //* ** public static double getQuotient(int dividend, int divisor) { return (double) (dividend / divisor); } // end getQuotient } // end class Division ByZero
Step by Step Solution
3.43 Rating (159 Votes )
There are 3 Steps involved in it
To handle an ArithmeticException that is thrown when dividing by zero the getQuotient method needs t... View full answer
Get step-by-step solutions from verified subject matter experts
