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

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

1 Expert Approved Answer
Step: 1 Unlock

To handle an ArithmeticException that is thrown when dividing by zero the getQuotient method needs t... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Introduction To Programming With Java A Problem Solving Approach Questions!