Startseite bisherige Projekte Tools/Snippets Bücherempfehlungen Publikationen Impressum Datenschutzerklärung

Hilfsklasse um Probleme mit Checked Exceptions zu umgehenSeptember 2016

Eine Hilfsklasse um Probleme mit Checked Exceptions zu umgehen.
Von mir weitgehend übernommen aus dem Blog-Post externer Link On Removing Java Checked Exceptions By Means of Perversion von James Iry.

package paConcepts;

import java.io.IOException;

/**
 * Helper class for wrapping checked exceptions in unchecked exceptions. See here:
 * 
 * http://james-iry.blogspot.de/2010/08/on-removing-java-checked-exceptions-by.html
 * 
 * Example
 * <pre>
 * 
 * public IndicationHeader getLastIndication() throws DBAccessException, UserCancelledException{
 *     Unchecked.chucks(UserCancelledException.class);
 *     
 *     return controller.runWithSession(session -> {
 *       try {
 *         return findPreviousHeaderForZeroOne(parent, controller, session); // throws UserCancelledException
 *       } catch (UserCancelledException e) {
 *         Unchecked.chuck(e);  // rethrow as unchecked exception
 *       }
 *       return null;
 *     });
 * }
 * </pre>    
 */
public class Unchecked {

  @SuppressWarnings("unchecked")
  private static <T extends Throwable, A> A pervertException(Throwable x) throws T {
    throw (T) x;
  }

  /**
   * Throws t as unchecked exception.
   * Can be used to re-throw an checked exception as unchecked.
   */
  public static <A> A chuck(Throwable t) {
    return Unchecked.<RuntimeException, A> pervertException(t);
  }

  /**
   * Used to mark that a method may throw a specific exception using chuck().
   */
  public static <T extends Throwable> void chucks(Class<T> clazz) throws T {
  }

  public static int testChuck() {
    return chuck(new IOException("unchecked, hellsyeah"));
  }

  public static void main(String[] args) {
    try {
      chucks(IOException.class);

      testChuck();
    } catch (IOException e) {
      System.out.println("Caught chucked exception " + e + ".");
    }
  }

}
Impressum - Datenschutzerklärung