-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestValid.java
74 lines (63 loc) · 2.47 KB
/
TestValid.java
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
import java.io.*;
import java.util.function.*;
import java.util.concurrent.Callable;
// this code is standard java and should produce no warnings or errors
public class TestValid {
private static final byte[] STARS = new byte[] { 42, 42, 42 };
public static void main(String [] args) {
// procedural code with checked exception handling
for (int i = 0; i < 1; i++) {
try { throw new Exception(); } catch (Exception e) { if (1 == 1) break; }
assert false;
}
try {
assert new String(STARS, "UTF-8").equals("***");
} catch (UnsupportedEncodingException e) {}
// traditional resource handling
OutputStream s = null;
try {
s = new ByteArrayOutputStream();
s.write((byte) 0);
} catch (IOException e) {
} finally {
try {
s.close();
} catch (IOException e) {}
}
// procedural code with unchecked exceptions
try { int i = 0; } catch (NullPointerException e) {}
// functional code without exceptions
((Consumer<Integer>) x -> {}).accept(1);
((Consumer<Integer>) x -> nop()).accept(1);
((Consumer<Integer>) x -> { return; }).accept(1);
((Consumer<Integer>) x -> { nop(); }).accept(1);
assert ((Function<Integer, Integer>) (x -> x)).apply(1).equals(1);
assert ((Function<Integer, Integer>) x -> { return one(); }).apply(5).equals(1);
// functional code with exception handling
((Runnable) () -> {
for (int i = 0; i < 1; i++) {
try { throw new Exception(); } catch (Exception e) { if (1 == 1) break; }
assert false;
}
}).run();
((Runnable) () -> {
try {
assert new String(STARS, "UTF-8").equals("***");
} catch (UnsupportedEncodingException e) {} // okay, never thrown
}).run();
// function as an anonymous class, no exceptions
assert new Function<String, String>() {
@Override public String apply(String name) {
return "hello " + name;
}
}.apply("world").equals("hello world");
}
private static int one() { return 1; }
private static void nop() {}
private static void declaredRuntimeException() throws RuntimeException {
throw new RuntimeException();
}
private static void undeclaredRuntimeException() {
throw new RuntimeException();
}
}