Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Chapter 12, excercise #5 Java Programming Ed.8 Write an application that throws

ID: 3805757 • Letter: C

Question

Chapter 12, excercise #5 Java Programming Ed.8                                                                                                                                                                                                          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 an appropriate message. Save file as SqrtException.java.

Explanation / Answer

SqrtException.java

import java.util.Scanner;

public class SqrtException {

   public static void main(String[] args) {
       //Declaring variable
       int number;
      
       //Scanner object is used to get the inputs entered by the user
       Scanner sc=new Scanner(System.in);

       //Getting the number entered by the user
       System.out.print("Enter the number :");
       number=sc.nextInt();
       try {
           /* if the user entered number is positive calculate the Square root of a number
           * if negative,throws ArithmeticException
           */
           if(number>=0)
           {
               System.out.println("The Square Root of "+number+" is :"+Math.sqrt(number));  
           }
           else
           {
               //Throwing Arithmetic Exception
               throw new ArithmeticException("** Could'nt find the square for Negative Number **");
           }
       } catch (Exception e) {
           //Displaying the Exception Here
           System.out.println("Exception :"+e);
       }
   }

}

__________________

output#1:

Enter the number :-4
Exception :java.lang.ArithmeticException: ** Could'nt find the square for Negative Number **

_________________

Output#2:

Enter the number :4
The Square Root of 4 is :2.0

_________________Thank You

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote