File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments