Exception Handling in Generics

Type parameters may be used in the throws clause of a method declaration, but (to preserve JVM compatibility) not in a catch clause. shows an example.

 Generic exception handling.

 public interface MyAction <E extends Exception> {

  public void doWork() throws E;

 }

 public class MyFileAction implements MyAction<FileNotFoundException> {

 public void doWork() throws FileNotFoundException {

   new File("/foo/bar.txt");

  // do something here...

 }

 }

 // client code

 MyFileAction fileAction = new MyFileAction();

  try {

   fileAction.doWork();

  }

  catch (FileNotFoundException e) {

   e.printStackTrace();

  } 

People who read this post also read :



0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More