For example,
2
then output should be
4
An "Number should be between 0 - 6" exception should be thrown if the number > 5 and number < 1.
Solution
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class RangeException extends Exception {
private int Number;
public RangeException(int number){
this.Number=number;
}
public String toString(){
return "Enter The Valid Number between 0 and 6";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.util.*;
public class UserDefinedException{
public static void main(String[] arg) throws Exception{
int number = getnumber();
try{
if ((number <= 0)|| (number >= 6))
throw new RangeException(number);
else{
number = number * number;
System.out.println("Square of the number is " + " "+ number);
}
}
finally
{
}
}
static int getnumber(){
Scanner input=new Scanner(System.in);
System.out.println("enter the number between 0 and 6");
int m =input.nextInt();
return m;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Output
enter the number between 0 and 6
2
Square of the number is 4
enter the number between 0 and 6
0
Exception in thread "main" Enter The Valid Number between 0 and 6
at UserDefinedException.main(UserDefinedException.java:7)
enter the number between 0 and 6
6
Exception in thread "main" Enter The Valid Number between 0 and 6
at UserDefinedException.main(UserDefinedException.java:7)
Post a Comment