Java Reference
In-Depth Information
< Day Day Up >
Puzzle 38: The Unwelcome Guest
The program in this puzzle models a system that attempts to read a user ID from its environment,
defaulting to a guest user if the attempt fails. The author of the program was faced with a situation
whereby the initializing expression for a static field could throw an exception. Because Java doesn't
allow static initializers to throw checked exceptions, the initialization must be wrapped in a try-
finally block. What does the program print?
public class UnwelcomeGuest {
public static final long GUEST_USER_ID = -1;
private static final long USER_ID;
static {
try {
USER_ID = getUserIdFromEnvironment();
} catch (IdUnavailableException e) {
USER_ID = GUEST_USER_ID;
System.out.println("Logging in as guest");
}
}
private static long getUserIdFromEnvironment()
throws IdUnavailableException {
throw new IdUnavailableException(); // Simulate an error
}
public static void main(String[] args) {
System.out.println("User ID: " + USER_ID);
 
 
Search WWH ::




Custom Search