Exception Handling in Static Initializer Blocks
Exception handling in static initializer blocks is no different from that in static initializer expressions: Uncaught checked exceptions cannot be thrown. Code in initializers cannot throw checked exceptions. A static initializer block cannot be called directly. Therefore, any checked exceptions must be caught and handled in the body of the static initializer block; otherwise, the compiler will issue an error. Example 10.5 shows a static initializer block at (3) that catches and handles a checked exception in the try-catch block at (4).
Example 10.5 Static Initializer Blocks and Exceptions
// File: ExceptionInStaticInitBlocks.java
package version1;
class TooManyCellsException extends Exception { // (1) Checked Exception
TooManyCellsException(String number) { super(number); }
}
//_____________________________________________________________________________
class Prison {
// Static Members
private static int noOfCells = 365;
private static int[] cells; // (2) No initializer expression
static { // (3) Static block
try { // (4) Handles checked exception
if (noOfCells > 300)
throw new TooManyCellsException(String.valueOf(noOfCells));
} catch (TooManyCellsException e) {
System.out.println(“Exception handled: ” + e);
noOfCells = 300;
System.out.println(“No. of cells adjusted to ” + noOfCells);
}
cells = new int[noOfCells];
}
}
//_____________________________________________________________________________
public class ExceptionInStaticInitBlocks {
public static void main(String[] args) {
new Prison();
}
}
Output from the program:
Exception handled: version1.TooManyCellsException: 365
No. of cells adjusted to 300
Static initializer blocks do not exactly aid code readability, and should be used sparingly, if at all. The code in the static initializer block at (3) in Example 10.5 can easily be refactored to instantiate the static array field cells at (2) using the private static method at (3) that handles the checked exception TooManyCellsException:
class Prison {
// Static Members
private static int noOfCells = 365;
private static int[] cells = initPrison(); // (2) Initializer expression
//
private static int[] initPrison() { // (3) Private static method
try { // (4) Handles checked exception
if (noOfCells > 300)
throw new TooManyCellsException(String.valueOf(noOfCells));
} catch (TooManyCellsException e) {
System.out.println(“Exception handled: ” + e);
noOfCells = 300;
System.out.println(“No. of cells adjusted to ” + noOfCells);
}
return new int[noOfCells];
}
}
Leave a Reply