fork download
  1. class Owner<T extends AutoCloseable> implements AutoCloseable {
  2. private T t;
  3.  
  4. public Owner(T t) {
  5. this.t = t;
  6. }
  7.  
  8. @Override
  9. public void close() throws Exception {
  10. if (t != null) {
  11. t.close();
  12. t = null;
  13. }
  14. }
  15.  
  16. public T release() {
  17. T result = t;
  18. t = null;
  19. return result;
  20. }
  21. }
  22.  
  23. class Bender implements AutoCloseable {
  24. private final String name;
  25. private final boolean bad;
  26.  
  27. public Bender(String name) throws Exception {
  28. throw new Exception(name + ": bite my shiny metal ass");
  29. }
  30.  
  31. public Bender(String name, boolean bad) {
  32. this.name = name;
  33. this.bad = bad;
  34. }
  35.  
  36. @Override
  37. public void close() throws Exception {
  38. if (bad) {
  39. throw new Exception(name + ": kill all humans");
  40. } else {
  41. System.out.println(name + ": all hail to hypnotoad");
  42. }
  43. }
  44. }
  45.  
  46. public class Main implements AutoCloseable {
  47. private Bender first;
  48. private Bender second;
  49.  
  50. public Main() throws Exception {
  51. try (Owner<Bender> first = new Owner<Bender>(new Bender("first", false))) {
  52. second = new Bender("second");
  53. this.first = first.release();
  54. }
  55. }
  56.  
  57. public Main(boolean bad) throws Exception {
  58. try (Owner<Bender> first = new Owner<Bender>(new Bender("first", false))) {
  59. second = new Bender("second", bad);
  60. this.first = first.release();
  61. }
  62. }
  63.  
  64. @Override
  65. public void close() throws Exception {
  66. try (Bender first = this.first; Bender second = this.second) {
  67. }
  68. }
  69.  
  70. public static void main(String[] args) {
  71. try (Main twr = new Main()) {
  72. System.out.println("first test");
  73. } catch (Exception e) {
  74. e.printStackTrace(System.out);
  75. }
  76. System.out.println();
  77.  
  78. try (Main twr = new Main(true)) {
  79. System.out.println("second test");
  80. } catch (Exception e) {
  81. e.printStackTrace(System.out);
  82. }
  83. System.out.println();
  84.  
  85. try (Main twr = new Main(false)) {
  86. System.out.println("third test");
  87. } catch (Exception e) {
  88. e.printStackTrace(System.out);
  89. }
  90. System.out.println();
  91. }
  92. }
  93.  
Success #stdin #stdout 0.06s 215552KB
stdin
Standard input is empty
stdout
first: all hail to hypnotoad
java.lang.Exception: second: bite my shiny metal ass
	at Bender.<init>(Main.java:28)
	at Main.<init>(Main.java:52)
	at Main.main(Main.java:71)

second test
first: all hail to hypnotoad
java.lang.Exception: second: kill all humans
	at Bender.close(Main.java:39)
	at Main.close(Main.java:67)
	at Main.main(Main.java:80)

third test
second: all hail to hypnotoad
first: all hail to hypnotoad