Exception Handling and Instance Initializer Blocks
Exception handling in instance initializer blocks is similar to that in static initializer blocks. Example 10.8 shows an instance initializer block at (3) that catches and handles a checked exception in the try-catch block at (4). Another instance initializer block at (5) throws an unchecked exception at (6). The runtime system handles the runtime exception, printing the stack trace and terminating the program.
Exception handling in instance initializer blocks differs from that in static initializer blocks in the following aspect: The execution of an instance initializer block can result in an uncaught checked exception, provided the exception is declared in the throws clause of every constructor in the class. Static initializer blocks cannot allow this, since no constructors are involved in class initialization. Instance initializer blocks in anonymous classes have even greater freedom: They can throw any exception.
Example 10.8 Exception Handling in Instance Initializer Blocks
// File: ExceptionsInInstBlocks.java
class RoomOccupancyTooHighException
extends Exception {} // (1) Checked exception
class BankruptcyException
extends RuntimeException {} // (2) Unchecked exception
//_______________________________________________________________________________
class Hotel {
// Instance Members
private boolean bankrupt = true;
private int noOfRooms = 215;
private int occupancyPerRoom = 5;
private int maxNoOfGuests;
{ // (3) Instance initializer block
try { // (4) Handles checked exception
if (occupancyPerRoom > 4)
throw new RoomOccupancyTooHighException();
} catch (RoomOccupancyTooHighException exception) {
System.out.println(“ROOM OCCUPANCY TOO HIGH: ” + occupancyPerRoom);
occupancyPerRoom = 4;
}
maxNoOfGuests = noOfRooms * occupancyPerRoom;
}
{ // (5) Instance initializer block
if (bankrupt)
throw new BankruptcyException(); // (6) Throws unchecked exception
} // …
}
//_______________________________________________________________________________
public class ExceptionsInInstBlocks {
public static void main(String[] args) {
new Hotel();
}
}
Output from the program:
ROOM OCCUPANCY TOO HIGH: 5
Exception in thread “main” BankruptcyException
at Hotel.<init>(ExceptionsInInstBlocks.java:27)
at ExceptionsInInstBlocks.main(ExceptionsInInstBlocks.java:33)
Leave a Reply