-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckTryWithResources.java
More file actions
54 lines (46 loc) · 1.4 KB
/
CheckTryWithResources.java
File metadata and controls
54 lines (46 loc) · 1.4 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
package ch.ocram.demo.trywithresources;
import java.io.Closeable;
import java.io.IOException;
public class CheckTryWithResources {
// tag::doSomething[]
public String doSomething(Config cfg) throws IOException {
try (Closeable c = getResource(cfg.failOnGetResource, cfg.failOnClose)) {
callSomeBusinessLogic(cfg.failOnBusinessLogic);
return "normallyExecuted";
} catch (Exception ex) {
handleException(cfg.failOnExceptionHandling);
return "exceptionHandled";
} finally {
doFinally(cfg.failOnFinally);
if (cfg.returnInFinally) {
return "returnedInFinally";
}
}
}
// end::doSomething[]
private void doFinally(boolean failOnFinally) {
if (failOnFinally) {
throw new RuntimeException("failedOnFinally");
}
}
private void handleException(boolean failOnExceptionHandling) {
if (failOnExceptionHandling) {
throw new RuntimeException("failedOnExceptionHandling");
}
}
private void callSomeBusinessLogic(boolean failOnBusinessLogic) {
if (failOnBusinessLogic) {
throw new RuntimeException("failedOnBusinessLogic");
}
}
private Closeable getResource(boolean failOnGetResource, boolean failOnClose) {
if (failOnGetResource) {
throw new RuntimeException("failedOnGetResource");
}
return () -> {
if (failOnClose) {
throw new RuntimeException("failedOnClose");
}
};
}
}