OnJava8-Examples/exceptions/CleanupIdiom.java

72 lines
1.7 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// exceptions/CleanupIdiom.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Disposable objects must be followed by a try-finally
2015-06-15 17:47:35 -07:00
class NeedsCleanup { // Construction can't fail
private static long counter = 1;
private final long id = counter++;
public void dispose() {
2015-12-15 11:47:04 -08:00
System.out.println(
"NeedsCleanup " + id + " disposed");
2015-06-15 17:47:35 -07:00
}
}
class ConstructionException extends Exception {}
class NeedsCleanup2 extends NeedsCleanup {
// Construction can fail:
public NeedsCleanup2() throws ConstructionException {}
}
public class CleanupIdiom {
public static void main(String[] args) {
2015-12-15 11:47:04 -08:00
// (1):
2015-06-15 17:47:35 -07:00
NeedsCleanup nc1 = new NeedsCleanup();
try {
// ...
} finally {
nc1.dispose();
}
2015-12-15 11:47:04 -08:00
// (2):
2015-06-15 17:47:35 -07:00
// If construction cannot fail you can group objects:
NeedsCleanup nc2 = new NeedsCleanup();
NeedsCleanup nc3 = new NeedsCleanup();
try {
// ...
} finally {
nc3.dispose(); // Reverse order of construction
nc2.dispose();
}
2015-12-15 11:47:04 -08:00
// (3):
2015-06-15 17:47:35 -07:00
// If construction can fail you must guard each one:
try {
NeedsCleanup2 nc4 = new NeedsCleanup2();
try {
NeedsCleanup2 nc5 = new NeedsCleanup2();
try {
// ...
} finally {
nc5.dispose();
}
2016-01-25 18:05:55 -08:00
} catch(ConstructionException e) { // nc5 const.
2015-06-15 17:47:35 -07:00
System.out.println(e);
} finally {
nc4.dispose();
}
2016-01-25 18:05:55 -08:00
} catch(ConstructionException e) { // nc4 const.
2015-06-15 17:47:35 -07:00
System.out.println(e);
}
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
NeedsCleanup 1 disposed
NeedsCleanup 3 disposed
NeedsCleanup 2 disposed
NeedsCleanup 5 disposed
NeedsCleanup 4 disposed
2015-09-07 11:44:36 -06:00
*/