The code relevant to the problem 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("Please enter a number: ");
userInput = scanner.next();
number = Double.parseDouble(userInput);
squareRootOfNumber = Math.sqrt(number);
if (number < 0) {
throw new ArithmeticException("Cannot compute the square root of a negative number");
}
System.out.format("The square root of the entered number is %.2f %n", squareRootOfNumber);
}
}
The program will output:
Please enter a number:
-90
Exception in thread "main" java.lang.ArithmeticException: Cannot compute the square root of a negative number at com..ans.Test.main(Test.java:18)
Explanation:
The standard Java library function java.lang.Math.sqrt does not throw an ArithmeticException for negative arguments, hence there’s no need to enclose your code in a try/catch block.
Instead, we manually trigger ArithmeticException using the throw keyword:
throw new ArithmeticException("Cannot compute the square root of a negative number");