Search⌘ K
AI Features

Solution: The Flight Boarding Protocol

Understand how to implement custom checked and unchecked exceptions in Java through a flight boarding protocol example. Learn to handle PassportExpiredException for recoverable errors and SecurityAlertException for critical failures, improving your ability to design robust exception handling logic.

We'll cover the following...
Java 25
// 1. Checked Exception (Must be handled or declared)
class PassportExpiredException extends Exception {}
// 2. Unchecked Exception (Runtime failure, stops flow implicitly)
class SecurityAlertException extends RuntimeException {}
public class BoardingSystem {
public static void tryBoarding(String status) {
try {
checkPassenger(status);
} catch (PassportExpiredException e) {
// Recoverable: We handle this and continue
System.out.println("Recovery: Refer to service desk.");
}
// We do NOT catch SecurityAlertException here; it crashes the app as intended.
}
// We must declare 'throws PassportExpiredException' because it is Checked
public static void checkPassenger(String status) throws PassportExpiredException {
if (status.equals("Expired")) {
throw new PassportExpiredException();
} else if (status.equals("Banned")) {
throw new SecurityAlertException();
} else {
System.out.println("Boarding successful.");
}
}
public static void main(String[] args) {
// Test 1: Handle recoverable error
System.out.println("--- Passenger 1: Expired Passport ---");
tryBoarding("Expired");
// Test 2: Handle critical error (Should crash the program)
System.out.println("\n--- Passenger 2: Security Risk ---");
tryBoarding("Banned");
}
}
...