You are here: Home / Topics / User defined exception example 2 in Java

User defined exception example 2 in Java

Filed under: Java on 2023-09-19 06:50:00

//  Program to create User-defined Exception
//  for checking validity of number for Square root.

class NegativeNumberException extends Exception 
{
private double num;

NegativeNumberException(double n) 
{
 num = n;
}

public String toString() 
{
 return "Square root of " + num + " is not possible.";
}
}

class  Exception15 
{
static void numberRoot(double n) throws NegativeNumberException
{
 System.out.println("Checking Number : (" + n + ")");
 if(n < 0)
  throw new NegativeNumberException(n);
 double r = Math.sqrt(n);
 System.out.println("Square Root of " + n + " is " + r + " .");
}

public static void main(String args[ ]) 
{
 try 
 {
  numberRoot(25);
  numberRoot(-5);
 } 
 catch (NegativeNumberException e) 
 {
  System.out.println("Caught: " + e);
 }
}
}

 

Output:

Checking Number : (25.0)
Square Root of 25.0 is 5.0
Checking Number : (-5.0)
Caught: Square root of -5.0 is not possible.

About Author:
M
Mr. Dubey     View Profile
Founder and CEO of MCQ Buddy. I just like to help others.