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)
*/
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
Post a Comment