-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathUserDefinedExceptionDemo.java
More file actions
41 lines (40 loc) · 1.45 KB
/
UserDefinedExceptionDemo.java
File metadata and controls
41 lines (40 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//Define two user defined exception ‘EvenNumberException’ and ‘OddNumberException’.
//Write a Java class which has a method which checks whether a given number if even or not.
//The method throws ‘EvenNumberException’ or ‘OddNumberException’ if the number is even or odd respectively.
//Illustrate the handling of the exception with suitable sequence of codes.
import java.util.Scanner;
class EvenNumberException extends Exception{
public EvenNumberException(String s){
// Call constructor of parent Exception
super(s);
}
}
class OddNumberException extends Exception{
public OddNumberException(String s){
// Call constructor of parent Exception
super(s);
}
}
public class UserDefinedExceptionDemo{
public static void main(String args[]){
try{
System.out.println("Enter an even or odd number:");
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
if(number%2==0){
throw new EvenNumberException("Even Number Exception");
}
else {
throw new OddNumberException("Odd Number Exception");
}
}
catch (EvenNumberException ex){
System.out.print("Caught-> ");
System.out.println(ex.getMessage());
}
catch (OddNumberException ex){
System.out.print("Caught ->");
System.out.println(ex.getMessage());
}
}
}