Implications for Exception Handling – Generics

Implications for Exception Handling

When an exception is thrown in a try block, it is matched against the parameter of each catch block that is associated with the try block. This test is similar to the instance test, requiring reifiable types. The following restrictions apply, and are illustrated in Example 11.17:

  • A generic type cannot extend the Throwable class.
  • A parameterized type cannot be specified in a throws clause.
  • The type of the parameter of a catch block must be a reifiable type, and it must also be a subtype of Throwable.

Example 11.17 Restrictions on Exception Handling

Click here to view code image

// File: ExceptionErrors.java
// (1) A generic class cannot extend Exception:
class MyGenericException<T> extends Exception { }        // Compile-time error!
public class ExceptionErrors {
  // (2) Cannot specify parameterized types in throws clause:
  public static void main(String[] args)
                     throws MyGenericException<String> { // Compile-time error!
    try {
      throw new MyGenericException<String>();
    } // (3) Cannot use parameterized type in catch block:
      catch (MyGenericException<String> e) {             // Compile-time error!
      e.printStackTrace();
    }
  }
}

However, type parameters are allowed in the throws clause, as shown in Example 11.18. In the declaration of the MyActionListener interface, the method doAction() can throw an exception of type E. The interface is implemented by the class FileAction, that provides the actual type parameter (FileNotFoundException) and implements the doAction() method with this actual type parameter. All is aboveboard, as only reifiable types are used for exception handling in the class FileAction.

Example 11.18 Type Parameter in throws Clause

Click here to view code image

public interface MyActionListener<E extends Exception> {
  public void doAction() throws E;       // Type parameter in throws clause
}
___________________________________________________________________________
import java.io.FileNotFoundException;
public class FileAction implements MyActionListener<FileNotFoundException> {
  @Override public void doAction() throws FileNotFoundException {
     throw new FileNotFoundException(“Does not exist”);
  }
  public static void main(String[] args) {
    FileAction fileAction = new FileAction();
    try {
      fileAction.doAction();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *