UserCodeException extends RuntimeException { public static UserCodeException wrap(Throwable t) { if (t instanceof UserCodeException) { return (UserCodeException) t; } return new UserCodeException(t); } private  UserCodeException(Throwable t); static UserCodeException wrap(Throwable t); static RuntimeException wrapIf(boolean condition, Throwable t);  }
@Test public void existingUserCodeExceptionsNotWrapped() { UserCodeException existing = UserCodeException.wrap(new IOException()); UserCodeException wrapped = UserCodeException.wrap(existing); assertEquals(existing, wrapped); }
@Test public void robustAgainstEmptyStackTrace() { RuntimeException runtimeException = new RuntimeException("empty stack"); runtimeException.setStackTrace(new StackTraceElement[0]); RuntimeException wrapped = UserCodeException.wrap(runtimeException); assertEquals(runtimeException, wrapped.getCause()); }