Start Page

Java: Throw checked exceptions without throws clause

Code that potentially throws checked exceptions, is often processed within a try-catch block. Two posibilities exist to forward caught exception to the caller:

  1. Wrap checked exception into an instance of RuntimeException.
  2. Declare a throws-clause

Both may be undesired. This article describes a technice to throw checked exceptions without the need of either. The technique is called throw sneaky. It is implemented as a static method:

@SuppressWarnings("unchecked")
public static <E extends Exception, R> R throwSneaky(Exception e)
  throws E {
  
  throw (E) e;
}
Java: Method throwSneaky

The code makes use of two things:

  1. The difference between checked and unchecked exceptions only exists during compile time.
  2. The potentially thrown checked Exception is hidden from the compiler with the help of Generics.

The following code sample will illustrate usage:

public static void main(String[] args) {
  try {
    new FileInputStream("nonexistent");
  } catch (FileNotFoundException e) {
    // Checked exception can be thrown
    // without throws clause.
    throwSneaky(e);
  }
}
Java: Sneaky Throw Usage Example

The technique described is inspired by a thread on stackoverflow.com. Although it does not spare you the try-catch-Block. This is addressed by Project Lombok with the Annotation @SneakyThrows.

Eclipse: Flip arguments with the help of regular expressions

Lately I have migrated a project from JUnit to TestNG. With the help of an Ecplipse plugin this is a one-click task. Every assert-method is replaced by its counterpart in class org.testng.AssertJUnit. This is only an intermediate solution. The final goal is to use org.testng.Assert. This will present a small challenge. JUnit's two arg assert-methods, e.g. assertEquals or assertSame expect order expected, actual. TestNG expect the opposite. Therefore argument order needs to be flipped.

Flipping argument order is achived with the help of Find/Replace and regular expressions. To find all assertEquals-methods and flip their arguments, follow 5 steps:

  1. Within the respective test class call the Find/Replace-dialog, either via menu entry Edit or via [Strg]-F.
  2. Check Regular expressions.
  3. Enter assertEquals\(([^,]+),\s*([^)]+)\s*\) into text field Find.
  4. Enter assertEquals(\2, \1) into text field Replace.
  5. Click button Replace All.
Eclipse: Find-Replace Dialog

The regular expression in text field Find makes use of two capturing groups. Capturing groups are created with ([^,]+) and ([^)]+). They are referenced in text field Replace in reverse order with \2 and \1.