Skip to content

Commit c3c5924

Browse files
author
turingfly
committed
Exceptions and Assertions
1 parent 5cd9ca3 commit c3c5924

File tree

5 files changed

+228
-3
lines changed

5 files changed

+228
-3
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package exceptionsAndAssertions;
2+
3+
/**
4+
*
5+
* @author chengfeili
6+
* Jun 11, 2017 11:25:30 AM
7+
*
8+
* An assertion is a Boolean expression that you place at a point in
9+
* your code where you expect something to be true.
10+
*
11+
* assert boolean_expression;
12+
* assert boolean_expression: error_message;
13+
*
14+
* If assertions are disabled, Java skips the assertion and goes on in
15+
* the code.
16+
* If assertions are enabled and the boolean expression is
17+
* true, then our assertion has been validated and nothing happens. The
18+
* program continues to execute in its normal manner.
19+
* If assertions are enabled and the boolean expression is false, then
20+
* our assertion is invalid and a java.lang.AssertionError is thrown.
21+
*
22+
* 1. Internal Invariants You assert that a value is within a certain constraint.
23+
* assert x < 0 is an example of an internal invariant.
24+
* 2. Class Invariants You assert the validity of an object’s state.
25+
* Class invariants are typically private methods within the class that return a boolean.
26+
* The upcoming Rectangle class demonstrates a class invariant.
27+
* 3. Control Flow Invariants You assert that a line of code you assume is unreachable is never reached.
28+
* The upcoming TestSeasons class demonstrates a control ow invariant.
29+
* 4. Preconditions You assert that certain conditions are met before a method is invoked.
30+
* 5. Post Conditions You assert that certain conditions are met after a method executes successfully.
31+
*/
32+
public class Assertions {
33+
public static void main(String[] args) {
34+
int numGuests = -5;
35+
assert numGuests > 0;
36+
System.out.println(numGuests);
37+
}
38+
}

Java-8/src/exceptionsAndAssertions/CommonExceptionTypes.java

+16-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
package exceptionsAndAssertions;
22

3-
import java.io.FileNotFoundException;
4-
import java.text.NumberFormat;
5-
63
/**
74
*
85
* @author chengfeili
@@ -40,12 +37,28 @@ public void runtimeException() {
4037

4138
// IllegalArgumentException
4239
throw new IllegalArgumentException("must not be negative");
40+
41+
// ArrayStoreException
42+
43+
// DateTimeException
44+
45+
// MissingResourceException
46+
47+
// IllegalStateException
48+
49+
// UnsupportedOperationException
4350
}
4451

4552
public void checkedException() {
4653
// FileNotFoundException // subclass of IOExcepption
4754

4855
// IOException;
56+
57+
// ParseException Converting a String to a number
58+
59+
// NotSerializableException
60+
61+
// SQLException
4962
}
5063

5164
public void errors() {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package exceptionsAndAssertions;
2+
3+
/**
4+
*
5+
* @author chengfeili
6+
* Jun 11, 2017 10:42:54 AM
7+
*
8+
* extend Exception(for checked)
9+
* extend RuntimeException(for unchecked)
10+
*
11+
*/
12+
13+
public class CreatingCustomExceptions extends Exception {
14+
public CreatingCustomExceptions() {
15+
super();
16+
}
17+
18+
public CreatingCustomExceptions(Exception e) {
19+
super(e);
20+
}
21+
22+
public CreatingCustomExceptions(String message) {
23+
super(message);
24+
}
25+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
package exceptionsAndAssertions;
2+
3+
import java.io.BufferedReader;
4+
import java.io.BufferedWriter;
5+
import java.io.IOException;
6+
import java.nio.file.Files;
7+
import java.nio.file.Path;
8+
9+
/**
10+
*
11+
* @author chengfeili
12+
* Jun 11, 2017 11:21:42 AM
13+
*
14+
* Remember that only a try-with-resources statement is permitted to
15+
* omit both the catch and finally blocks. A traditional try statement
16+
* must have either or both.
17+
*/
18+
public class TryWithResources {
19+
/**
20+
*
21+
* The new try-with-resources statement automatically closes all
22+
* resources opened in the try clause. This feature is also
23+
* known as automatic resource management, because Java
24+
* automatically takes care of the closing.
25+
*
26+
* The resources created in the try clause are only in scope within the try block.
27+
*/
28+
public void newApproach(Path path1, Path path2) throws IOException {
29+
try (BufferedReader in = Files.newBufferedReader(path1);
30+
BufferedWriter out = Files.newBufferedWriter(path2)) {
31+
out.write(in.readLine());
32+
}
33+
}
34+
}
35+
36+
/**
37+
* AutoCloseable
38+
*
39+
* You can’t just put any random class in a try-with-resources statement. Java
40+
* commits to closing automatically any resources opened in the try clause.
41+
*
42+
*/
43+
class TurkeyCage implements AutoCloseable {
44+
public void close() {
45+
System.out.println("Close gate");
46+
}
47+
48+
public static void main(String[] args) {
49+
try (TurkeyCage t = new TurkeyCage()) {
50+
System.out.println("put turkeys in");
51+
}
52+
}
53+
}
54+
55+
/**
56+
*
57+
* What happens if the try block also throws an exception? Java 7 added a way to
58+
* accumulate exceptions. When multiple exceptions are thrown, all but the first
59+
* are called suppressed exceptions.
60+
*
61+
*/
62+
class JammedTurkeyCage implements AutoCloseable {
63+
public void close() throws IllegalStateException {
64+
throw new IllegalStateException("Cage door does not close");
65+
}
66+
// print
67+
// caught: turkeys ran off
68+
// Cage door does not close
69+
public static void main(String[] args) {
70+
try (JammedTurkeyCage t = new JammedTurkeyCage()) {
71+
throw new IllegalStateException("turkeys ran off");
72+
} catch (IllegalStateException e) {
73+
System.out.println("caught: " + e.getMessage());
74+
for (Throwable t : e.getSuppressed())
75+
System.out.println(t.getMessage());
76+
}
77+
}
78+
}
79+
80+
/**
81+
*
82+
* Resources are closed after the try clause ends and before any catch/finally clauses.
83+
* Resources are closed in the reverse order from which they were
84+
* created.
85+
*
86+
* Print:
87+
* Close: 2
88+
* Close: 1
89+
* ex
90+
* finally
91+
*/
92+
class Auto implements AutoCloseable {
93+
int num;
94+
95+
Auto(int num) {
96+
this.num = num;
97+
}
98+
99+
public void close() {
100+
System.out.println("Close: " + num);
101+
}
102+
103+
public static void main(String[] args) {
104+
try (Auto a1 = new Auto(1); Auto a2 = new Auto(2)) {
105+
throw new RuntimeException();
106+
} catch (Exception e) {
107+
System.out.println("ex");
108+
} finally {
109+
System.out.println("finally");
110+
}
111+
}
112+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package exceptionsAndAssertions;
2+
3+
import java.io.IOException;
4+
import java.nio.file.Files;
5+
import java.nio.file.Path;
6+
import java.nio.file.Paths;
7+
import java.time.LocalDate;
8+
import java.time.format.DateTimeParseException;
9+
10+
/**
11+
*
12+
* @author chengfeili
13+
* Jun 11, 2017 10:45:57 AM
14+
*
15+
*/
16+
public class UsingMultiCatch {
17+
public static void main(String[] args) {
18+
try {
19+
Path path = Paths.get("a.txt");
20+
String text = new String(Files.readAllBytes(path));
21+
LocalDate date = LocalDate.parse(text);
22+
System.out.println(date);
23+
} catch (DateTimeParseException | IOException e) {
24+
e.printStackTrace();
25+
throw new RuntimeException(e);
26+
}
27+
28+
/**
29+
*
30+
try {
31+
throw new IOException();
32+
} catch(IOException | RuntimeException e) {
33+
e = new RuntimeException(); // DOES NOT COMPILE
34+
}
35+
*/
36+
}
37+
}

0 commit comments

Comments
 (0)