-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvalidAgeHandler.java
More file actions
33 lines (28 loc) · 1.08 KB
/
Copy pathInvalidAgeHandler.java
File metadata and controls
33 lines (28 loc) · 1.08 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
import java.util.InputMismatchException;
import java.util.Scanner;
// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class InvalidAgeHandler {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your age: ");
int age = scanner.nextInt();
if (age < 0 || age > 150) {
throw new InvalidAgeException("Invalid age! Age must be between 0 and 150.");
}
System.out.println("Your age is valid: " + age);
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage());
} catch (InputMismatchException e) {
System.out.println("Error: Please enter a valid integer for age.");
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
System.out.println("Age validation completed.");
}
}
}