forked from tugul/CoreJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTryWithResource.java
More file actions
78 lines (68 loc) · 2 KB
/
Copy pathTryWithResource.java
File metadata and controls
78 lines (68 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package exception;
import java.io.Closeable;
/**
* - Try statement
* must be followed by either or both of catch and finally blocks
* requires tedious work to declare resources outside block and to close them in finally block
*
* - Try with resource
* introduced in Java 7
* doesn't require any catch or finally block
* resource is automatically closed at the end of try block (implicit finally block is executed)
* Resource class must implement interface java.lang.AutoClosable
* If several resource are opened, they are closed in reverse order
*
* - java.io.Closeable
* resource can implement this interface as it extends interface AutoClosable
* its close only throws IOException while AutoClosable's close can throw any exception
*
*/
class Box implements AutoCloseable {
int id;
public Box(int size) {
this.id = size;
}
@Override
public void close() throws RuntimeException {
System.out.println("Box " + id +" is closed");
}
}
class FragileBox implements Closeable {
@Override
public void close() throws RuntimeException {
throw new RuntimeException("can't close");
}
}
class BrokenBox implements AutoCloseable {
@Override
public void close() throws Exception {
}
}
public class TryWithResource {
public static void main(String[] args) {
try (Box box1 = new Box(10);
Box box2 = new Box(20)){
System.out.println("Look inside the box");
}
try(FragileBox box = new FragileBox()){
System.out.println("Box is open");
}
catch (RuntimeException e){
System.out.println("Caught: " + e.getMessage());
}
finally {
System.out.println("Oh, finally!");
}
try (BrokenBox bb = new BrokenBox()){ // DOES NOT COMPILE, checked exception is not handled or declared
}
finally{}
}
}
/* It prints:
Look inside the box
Box 20 is closed
Box 10 is closed
Box is open
Caught: can't close
Oh, finally!
*/