Exception_Handling Program

Create an exception class named NegativeNumberException extended from the class Exception. This class should contain a parameterless constructor to call the Exception class constructor with the message “You should enter a positive number”. Create a class named exercise3 that contains:

a) A method named M1 that accepts a double variable as argument and returns its square root. The method should throw the NegativeNumberException exception defined above.

b) The main method to prompt the user to enter a number and then to call the method M1 (insert a try-catch block to handle the NegativeNumberException exception).



package javaapplication5;

import java.util.*;

class NegativeNumberException extends Exception
{
public NegativeNumberException()
{
super("You should enter a

Positive Number.");
}
}
public class JavaApplication5
{
public static void main (String[] args)
{
        Scanner s;
                    s = new Scanner(System.in);
  try
{
  System.out.println

("Enter a number :");
  double n = s.nextInt();
  System.out.println(M1

(n));
  }
        catch

(NegativeNumberException e )
{
    System.out.println(e);
  }

  }
  public static double M1(double x)throws

NegativeNumberException
  {
  if(x < 0) throw new

NegativeNumberException();
    return Math.sqrt(x);
}
}


/* OUTPUT:
run:
Enter a number :
4
2.0
BUILD SUCCESSFUL (total time: 4 seconds)

run:
Enter a number :
-4
javaapplication5.NegativeNumberException: You

should enter a Positive Number.
BUILD SUCCESSFUL (total time: 4 seconds)
*/

Comments

Popular posts from this blog

Write a java program to create an abstract class named Shape that contains two integers and an abstract method named printArea(). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contain only the method printArea( ) that prints the area of the given shape.

Create Employee Class with Method getdata and setdata. Create following subclasses to generate biodata. i) Personal record ii)) Professional record iii) Academic record Assume appropriate data members and member function to accept required data & print bio-data. Use Overriding at suitable places.Create bio-data using multilevel inheritances.