Skip to content

Commit c93e454

Browse files
committed
Program 4.2
1 parent 980daca commit c93e454

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

ucer/4B4/4_2.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.Scanner;
2+
3+
// User-defined (custom) checked exception
4+
class InvalidAgeException extends Exception {
5+
public InvalidAgeException(String message) {
6+
super(message);
7+
}
8+
}
9+
10+
class CustomExceptionDemo {
11+
12+
// Method that throws the custom exception
13+
public static void checkAge(int age) throws InvalidAgeException {
14+
if (age < 18) {
15+
throw new InvalidAgeException("Age must be 18 or older to register.");
16+
} else {
17+
System.out.println("Age is valid. You are eligible to register.");
18+
}
19+
}
20+
21+
public static void main(String[] args) {
22+
Scanner scanner = new Scanner(System.in);
23+
24+
try {
25+
System.out.print("Enter your age: ");
26+
int age = scanner.nextInt();
27+
28+
// Call method that may throw custom exception
29+
checkAge(age);
30+
} catch (InvalidAgeException e) {
31+
System.out.println("Custom Exception Caught: " + e.getMessage());
32+
} catch (Exception e) {
33+
System.out.println("Unexpected error: " + e);
34+
} finally {
35+
// Cleanup or final message
36+
System.out.println("Execution completed. Thank you!");
37+
scanner.close();
38+
}
39+
}
40+
}
41+

0 commit comments

Comments
 (0)