Guest User

Untitled

a guest
Apr 23rd, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. InitializeStuff();
  2. try
  3. {
  4. DoSomeWork();
  5. }
  6. catch
  7. {
  8. UndoInitialize();
  9. throw;
  10. }
  11.  
  12. InitializeStuff();
  13. try
  14. {
  15. DoSomeWork();
  16. }
  17. catch
  18. {
  19. UndoInitialize();
  20. throw;
  21. }
  22.  
  23. public final class Rethrow {
  24.  
  25. private Rethrow() { throw new AssertionError("uninstantiable"); }
  26.  
  27. /** Rethrows t if it is an unchecked exception. */
  28. public static void unchecked(Throwable t) {
  29. if (t instanceof Error)
  30. throw (Error) t;
  31. if (t instanceof RuntimeException)
  32. throw (RuntimeException) t;
  33. }
  34.  
  35. /** Rethrows t if it is an unchecked exception or an instance of E. */
  36. public static <E extends Exception> void instanceOrUnchecked(
  37. Class<E> exceptionClass, Throwable t) throws E, Error,
  38. RuntimeException {
  39. Rethrow.unchecked(t);
  40. if (exceptionClass.isInstance(t))
  41. throw exceptionClass.cast(t);
  42. }
  43.  
  44. }
  45.  
  46. public void doStuff() throws SomeException {
  47. initializeStuff();
  48. try {
  49. doSomeWork();
  50. } catch (Throwable t) {
  51. undoInitialize();
  52. Rethrow.instanceOrUnchecked(SomeException.class, t);
  53. // We shouldn't get past the above line as only unchecked or
  54. // SomeException exceptions are thrown in the try block, but
  55. // we don't want to risk swallowing an error, so:
  56. throw new SomeException("Unexpected exception", t);
  57. }
  58. private void doSomeWork() throws SomeException { ... }
  59. }
  60.  
  61. boolean okay = false;
  62. try {
  63. // do some work which might throw an exception
  64. okay = true;
  65. } finally {
  66. if (!okay) // do some clean up.
  67. }
  68.  
  69. try {
  70. // do some work which might throw an exception
  71. } catch (Throwable t) {
  72. // do something with t.
  73. Thread.currentThread().stop(t);
  74. }
  75.  
  76. public static SomeException throwException(String message, Throwable cause) throws SomeException {
  77. unchecked(cause); //calls the method you defined in the question.
  78. throw new SomeException(message, cause);
  79. }
  80.  
  81. catch (Throwable e) {
  82. undoInitialize();
  83. throw SomeException.throwException("message", e);
  84. }
  85.  
  86. public SomeException(message, cause) {
  87. super(message, unchecked(cause));
  88. }
  89.  
  90. private static Throwable unchecked(Throwable cause) {
  91. if (cause instanceof Error) throw (Error) cause;
  92. if (cause instanceof RuntimeException) throw (RuntimeException) cause;
  93. return cause;
  94. }
Add Comment
Please, Sign In to add comment