Start

Java: Throw checked exceptions without throws clause

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

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

Both possibillities 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 in class Sneaker as a static method:

public final class Sneaker {

  @SuppressWarnings("unchecked")
  public static <T extends Throwable> T throwSneaky(Throwable t)
    throws T {
    throw (T) t;
  }

  Sneaker() { throw new Error("no instances please"); }
}
Sneaker.java

The code makes use of two things:

  1. The difference between checked und unchecked exceptions only exists during compile time.
  2. The checked Exception potentially being thrown, is hidden to the compiler by the generic method argument <T extends Throwable>.

The following code sample will illustrate the usage:

// no throws clause
public static void main(String[] args) {
  try {
    new FileInputStream("nonexistent");
  } catch (FileNotFoundException e) {
    // FileNotFoundException can be thrown
    // without throws clause.
    throw Sneaker.throwSneaky(e);
  }
}
Sneaker – Usage

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

Eclipse: Flip argument order using 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 use order expected, actual. TestNG uses 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 respetive test class call the Find/Replace-dialogue, 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

The trick is to use regular expressions not only for matching but also for capturing several parts of the searched string into Capturing Groups. Those can be referenced by their number of occurrence starting at one. Capturing groups will be created with ([^,]+) and ([^)]+). They are referenced in flipped order with \1 and \2.