Skip to content

Instantly share code, notes, and snippets.

@mikaelhg
Created February 13, 2013 08:27
Show Gist options
  • Save mikaelhg/4943081 to your computer and use it in GitHub Desktop.
Save mikaelhg/4943081 to your computer and use it in GitHub Desktop.
AutocloseableDemo
package com.gueck.dogdash;
public class AutocloseableDemo {
private static class CreateException extends RuntimeException {}
private static class CloseException extends RuntimeException {}
private static class OperationException extends RuntimeException {}
private static abstract class BasicOperable {
public void operate() throws OperationException {}
}
private static class Create extends BasicOperable implements AutoCloseable {
public Create() throws CreateException {
System.err.println("create: calling create");
throw new CreateException();
}
@Override
public void close() throws CreateException {
System.err.println("create: calling close");
}
}
private static class Close extends BasicOperable implements AutoCloseable {
public Close() {
System.err.println("close: calling create");
}
@Override
public void close() throws CloseException {
System.err.println("close: calling close");
throw new CloseException();
}
}
private static class Operate extends BasicOperable implements AutoCloseable {
public Operate() {
System.err.println("operate: calling create");
}
@Override
public void close() throws CloseException {
System.err.println("operate: calling close");
}
@Override
public void operate() throws OperationException {
System.err.println("operate: calling operate");
throw new OperationException();
}
}
public static void main(final String ... args) {
try(final Create create = new Create()) {
create.operate();
} catch (final CreateException e) {
System.err.println("create: create exception");
} catch (final OperationException e) {
System.err.println("create: operation exception");
} catch (final CloseException e) {
System.err.println("create: close exception");
}
try(final Close close = new Close()) {
close.operate();
} catch (final CreateException e) {
System.err.println("close: create exception");
} catch (final OperationException e) {
System.err.println("close: operation exception");
} catch (final CloseException e) {
System.err.println("close: close exception");
}
try(final Operate operate = new Operate()) {
operate.operate();
} catch (final CreateException e) {
System.err.println("operate: create exception");
} catch (final OperationException e) {
System.err.println("operate: operation exception");
} catch (final CloseException e) {
System.err.println("operate: close exception");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment