Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- InitializeStuff();
- try
- {
- DoSomeWork();
- }
- catch
- {
- UndoInitialize();
- throw;
- }
- InitializeStuff();
- try
- {
- DoSomeWork();
- }
- catch
- {
- UndoInitialize();
- throw;
- }
- public final class Rethrow {
- private Rethrow() { throw new AssertionError("uninstantiable"); }
- /** Rethrows t if it is an unchecked exception. */
- public static void unchecked(Throwable t) {
- if (t instanceof Error)
- throw (Error) t;
- if (t instanceof RuntimeException)
- throw (RuntimeException) t;
- }
- /** Rethrows t if it is an unchecked exception or an instance of E. */
- public static <E extends Exception> void instanceOrUnchecked(
- Class<E> exceptionClass, Throwable t) throws E, Error,
- RuntimeException {
- Rethrow.unchecked(t);
- if (exceptionClass.isInstance(t))
- throw exceptionClass.cast(t);
- }
- }
- public void doStuff() throws SomeException {
- initializeStuff();
- try {
- doSomeWork();
- } catch (Throwable t) {
- undoInitialize();
- Rethrow.instanceOrUnchecked(SomeException.class, t);
- // We shouldn't get past the above line as only unchecked or
- // SomeException exceptions are thrown in the try block, but
- // we don't want to risk swallowing an error, so:
- throw new SomeException("Unexpected exception", t);
- }
- private void doSomeWork() throws SomeException { ... }
- }
- boolean okay = false;
- try {
- // do some work which might throw an exception
- okay = true;
- } finally {
- if (!okay) // do some clean up.
- }
- try {
- // do some work which might throw an exception
- } catch (Throwable t) {
- // do something with t.
- Thread.currentThread().stop(t);
- }
- public static SomeException throwException(String message, Throwable cause) throws SomeException {
- unchecked(cause); //calls the method you defined in the question.
- throw new SomeException(message, cause);
- }
- catch (Throwable e) {
- undoInitialize();
- throw SomeException.throwException("message", e);
- }
- public SomeException(message, cause) {
- super(message, unchecked(cause));
- }
- private static Throwable unchecked(Throwable cause) {
- if (cause instanceof Error) throw (Error) cause;
- if (cause instanceof RuntimeException) throw (RuntimeException) cause;
- return cause;
- }
Add Comment
Please, Sign In to add comment