// exceptions/CleanupIdiom.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.// Disposable objects must be followed by a try-finallyclass NeedsCleanup { // Construction can't failprivate static long counter = 1;private final long id = counter++;public void dispose() {System.out.println("NeedsCleanup " + id + " disposed");}}class ConstructionException extends Exception {}class NeedsCleanup2 extends NeedsCleanup {// Construction can fail:NeedsCleanup2() throws ConstructionException {}}public class CleanupIdiom {public static void main(String[] args) {// [1]:NeedsCleanup nc1 = new NeedsCleanup();try {// ...} finally {nc1.dispose();}// [2]:// If construction cannot fail,// you can group objects:NeedsCleanup nc2 = new NeedsCleanup();NeedsCleanup nc3 = new NeedsCleanup();try {// ...} finally {nc3.dispose(); // Reverse order of constructionnc2.dispose();}// [3]:// If construction can fail you must guard each one:try {NeedsCleanup2 nc4 = new NeedsCleanup2();try {NeedsCleanup2 nc5 = new NeedsCleanup2();try {// ...} finally {nc5.dispose();}} catch(ConstructionException e) { // nc5 const.System.out.println(e);} finally {nc4.dispose();}} catch(ConstructionException e) { // nc4 const.System.out.println(e);}}}/* Output:NeedsCleanup 1 disposedNeedsCleanup 3 disposedNeedsCleanup 2 disposedNeedsCleanup 5 disposedNeedsCleanup 4 disposed*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。