Write an application that throws and catches an ArithmeticException when you attempt to take the square root of a negative value. Prompt the user for an input value and try the Math.sqrt() method on it. The application either displays the square root or catches the thrown Exception and displays the message Can't take square root of negative number

Respuesta :

kanat

The code for the program described in question:

import java.util.Scanner;

public class Test {

   public static void main(String[] args) {

       double number;

       double squareRootOfNumber;

       String userInput = null;

       Scanner scanner = new Scanner(System.in);

       System.out.println("Enter the number: ");

       userInput = scanner.next();

       number = Double.parseDouble(userInput);

       squareRootOfNumber = Math.sqrt(number);

       if (number < 0) {

           throw new ArithmeticException("Can't take square root of negative number");

       }

       System.out.format("Square root of number entered is %.2f %n", squareRootOfNumber);

   }

}

The output of the program will be:

Enter the number:

-90

Exception in thread "main" java.lang.ArithmeticException: Can't take square root of negative number at com.brainly.ans.Test.main(Test.java:18)

Explanation:

Function from standard Java library java.lang.Math.sqrt will not throw an ArithmeticException even its argument is negative so there is no reason to surround your code try/catch block.

Instead, we have thrown ArithmeticException manually by using throw keyword:

throw new ArithmeticException("Can't take square root of negative number");

ACCESS MORE