12. Exceptions
12.1. Divide by zero example
1var a = 10;
2var b = 0;
3var c = a / b;
12.2. try-catch
1var a = 10;
2var b = 0;
3
4try {
5 var c = a / b;
6 System.out.println(a + " / " + b + " = " + c);
7} catch (ArithmeticException e) {
8 System.out.println(a + " / " + b + " => " + e);
9}
12.3. throw
1var a = 10;
2var b = 0;
3
4try {
5 var c = a / b;
6 System.out.println(a + " / " + b + " = " + c);
7} catch (ArithmeticException e) {
8 throw new ArithmeticException(a + " / " + b + " => " + e);
9}
12.4. try-catch-finally
1var a = 10;
2var b = 0;
3var c = -1;
4
5try {
6 c = a / b;
7} catch (ArithmeticException e) {
8 // swallow
9} finally {
10 if (c == -1) {
11 System.err.println(a + " / " + b + " cannot be computed");
12 }
13}
12.5. try-catch with resources
1import com.opencsv.CSVParserBuilder;
2import com.opencsv.CSVReaderBuilder;
3import com.opencsv.CSVWriterBuilder;
4import com.opencsv.ICSVParser;
5import com.opencsv.ICSVWriter;
6import java.io.FileReader;
7import java.io.FileWriter;
1try (var writer = new CSVWriterBuilder(new FileWriter("demo.csv"))
2 .withSeparator(ICSVParser.DEFAULT_SEPARATOR)
3 .withQuoteChar(ICSVParser.DEFAULT_QUOTE_CHARACTER)
4 .withEscapeChar(ICSVParser.DEFAULT_ESCAPE_CHARACTER)
5 .withLineEnd(ICSVWriter.DEFAULT_LINE_END)
6 .build()) {
7
8 var entries = new String[][] {
9 { "first_name", "last_name" },
10 { "John", "Doe" },
11 { "Jane", "Smith" }
12 };
13
14 for (String[] row : entries) {
15 writer.writeNext(row);
16 }
17}
18
19final var parser = new CSVParserBuilder()
20 .withSeparator(ICSVParser.DEFAULT_SEPARATOR)
21 .withQuoteChar(ICSVParser.DEFAULT_QUOTE_CHARACTER)
22 .withEscapeChar(ICSVParser.DEFAULT_ESCAPE_CHARACTER)
23 .build();
24
25try (var reader = new CSVReaderBuilder(new FileReader("demo.csv"))
26 .withSkipLines(1)
27 .withCSVParser(parser)
28 .build()) {
29 String[] line;
30 while ((line = reader.readNext()) != null) {
31 for (int i = 0; i < line.length; i++) {
32 System.out.print(line[i]);
33 if (i < line.length - 1) {
34 System.out.print(", ");
35 } else if (i == line.length - 1) {
36 System.out.println();
37 }
38 }
39 }
40}