OnJava8-Examples/exceptions/CloseExceptions.java

49 lines
1.1 KiB
Java
Raw Normal View History

2015-12-15 11:47:04 -08:00
// exceptions/CloseExceptions.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-12-15 11:47:04 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-12-15 11:47:04 -08:00
class CloseException extends Exception {}
class Reporter2 implements AutoCloseable {
String name = getClass().getSimpleName();
2017-05-01 14:33:10 -06:00
Reporter2() {
2015-12-15 11:47:04 -08:00
System.out.println("Creating " + name);
}
public void close() throws CloseException {
System.out.println("Closing " + name);
}
}
class Closer extends Reporter2 {
@Override
public void close() throws CloseException {
super.close();
throw new CloseException();
}
}
public class CloseExceptions {
public static void main(String[] args) {
try(
First f = new First();
Closer c = new Closer();
Second s = new Second()
) {
2015-12-15 11:47:04 -08:00
System.out.println("In body");
} catch(CloseException e) {
System.out.println("Caught: " + e);
}
}
}
/* Output:
Creating First
Creating Closer
Creating Second
In body
Closing Second
Closing Closer
Closing First
Caught: CloseException
*/