Просмотр исходного кода

Add new exercise Error Handling (#1338)

* Add new exercise Error Handling

* Add requested changes

* Undo unnecessary change to ErrorHandlingTest.java

* Add requested changes

* Add requested changes

* Check exception message

* Add requested changes to ErrorHandlingTest.java

* Add hints.md

* Add requested suggestions

* Expand hints.md

* Add gramatical suggestions
Cristian Rivas Gómez 8 лет назад
Родитель
Сommit
be509782d0

+ 11
- 0
config.json Просмотреть файл

398
     {
398
     {
399
       "core": false,
399
       "core": false,
400
       "difficulty": 4,
400
       "difficulty": 4,
401
+      "slug": "error-handling",
402
+      "topics": [
403
+        "exception_handling",
404
+        "optional_values"
405
+      ],
406
+      "unlocked_by": "triangle",
407
+      "uuid": "846ae792-7ca7-43e1-b523-bb1ec9fa08eb"
408
+    },
409
+    {
410
+      "core": false,
411
+      "difficulty": 4,
401
       "slug": "diamond",
412
       "slug": "diamond",
402
       "topics": [
413
       "topics": [
403
         "arrays",
414
         "arrays",

+ 35
- 0
exercises/error-handling/.meta/hints.md Просмотреть файл

1
+This exercise requires you to handle exceptions. An [exception](https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html) is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
2
+
3
+In Java, there are two types of exceptions: checked and unchecked exceptions.
4
+
5
+- [Checked vs Unchecked Exceptions in Java](https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/)
6
+
7
+- [Unchecked Exceptions — The Controversy](https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html)
8
+
9
+## Checked exceptions
10
+
11
+Checked exceptions are the exceptions that are checked at [compile time](https://en.wikipedia.org/wiki/Compile_time).
12
+
13
+### Practical implications
14
+
15
+You have to declare them in the [method signature](https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html) of any method that can [throw](https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html) a checked exception and handle or rethrow them when calling any method that can throw a checked exception.
16
+
17
+This is because checked exceptions are meant to be handled at runtime, i.e. they are errors you can recover from.
18
+
19
+### Examples of where they are used
20
+
21
+They're often used when a method can't return any valid result, for example a search method which hasn't found the item it was searching for.
22
+
23
+It's an alternative to returning null or a error code. A checked exception is better than those alternatives because it forces the user of the method to consider the error case.
24
+
25
+## Unchecked exceptions
26
+
27
+Unchecked exceptions are the exceptions that are not checked at [compile time](https://en.wikipedia.org/wiki/Compile_time).
28
+
29
+### Practical implications
30
+
31
+You don't have to declare them in the [method signature](https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html) of methods that can [throw](https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html) an unchecked exception and handle or rethrow them when calling any method that can throw an unchecked exception.
32
+
33
+### Examples of where they are used
34
+
35
+Unchecked exceptions are mean to be used for any error than can't be handled at runtime, e.g. running out of memory.

+ 11
- 0
exercises/error-handling/.meta/src/reference/java/CustomCheckedException.java Просмотреть файл

1
+class CustomCheckedException extends Exception {
2
+
3
+    CustomCheckedException() {
4
+        super();
5
+    }
6
+
7
+    CustomCheckedException(String message) {
8
+        super(message);
9
+    }
10
+
11
+}

+ 11
- 0
exercises/error-handling/.meta/src/reference/java/CustomUncheckedException.java Просмотреть файл

1
+class CustomUncheckedException extends RuntimeException {
2
+
3
+    CustomUncheckedException() {
4
+        super();
5
+    }
6
+
7
+    CustomUncheckedException(String message) {
8
+        super(message);
9
+    }
10
+
11
+}

+ 63
- 0
exercises/error-handling/.meta/src/reference/java/ErrorHandling.java Просмотреть файл

1
+import java.io.IOException;
2
+import java.util.Optional;
3
+
4
+class ErrorHandling {
5
+
6
+    void handleErrorByThrowingIllegalArgumentException() {
7
+        throw new IllegalArgumentException();
8
+    }
9
+
10
+    void handleErrorByThrowingIllegalArgumentExceptionWithDetailMessage(String message) {
11
+        throw new IllegalArgumentException(message);
12
+    }
13
+
14
+    void handleErrorByThrowingAnyCheckedException() throws IOException {
15
+        throw new IOException();
16
+    }
17
+
18
+    void handleErrorByThrowingAnyCheckedExceptionWithDetailMessage(String message) throws IOException {
19
+        throw new IOException(message);
20
+    }
21
+
22
+    void handleErrorByThrowingAnyUncheckedException() {
23
+        throw new NullPointerException();
24
+    }
25
+
26
+    void handleErrorByThrowingAnyUncheckedExceptionWithDetailMessage(String message) {
27
+        throw new NullPointerException(message);
28
+    }
29
+
30
+    void handleErrorByThrowingCustomCheckedException() throws CustomCheckedException {
31
+        throw new CustomCheckedException();
32
+    }
33
+
34
+    void handleErrorByThrowingCustomCheckedExceptionWithDetailMessage(String message) throws CustomCheckedException {
35
+        throw new CustomCheckedException(message);
36
+    }
37
+
38
+    void handleErrorByThrowingCustomUncheckedException() {
39
+        throw new CustomUncheckedException();
40
+    }
41
+
42
+    void handleErrorByThrowingCustomUncheckedExceptionWithDetailMessage(String message) {
43
+        throw new CustomUncheckedException(message);
44
+    }
45
+
46
+    Optional<Integer> handleErrorByReturningOptionalInstance(String integer) {
47
+        if (tryParseInt(integer)) {
48
+            return Optional.of(Integer.parseInt(integer));
49
+        } else {
50
+            return Optional.empty();
51
+        }
52
+    }
53
+
54
+    private boolean tryParseInt(String integer) {
55
+        try {
56
+            Integer.parseInt(integer);
57
+            return true;
58
+        } catch (NumberFormatException e) {
59
+            return false;
60
+        }
61
+    }
62
+
63
+}

+ 24
- 0
exercises/error-handling/README.md Просмотреть файл

1
+# Error Handling
2
+
3
+Implement various kinds of error handling and resource management.
4
+
5
+An important point of programming is how to handle errors and close
6
+resources even if errors occur.
7
+
8
+This exercise requires you to handle various errors. Because error handling
9
+is rather programming language specific you'll have to refer to the tests
10
+for your track to see what's exactly required.
11
+
12
+# Running the tests
13
+
14
+You can run all the tests for an exercise by entering
15
+
16
+```sh
17
+$ gradle test
18
+```
19
+
20
+in your terminal.
21
+
22
+## Submitting Incomplete Solutions
23
+
24
+It's possible to submit an incomplete solution so you can see how others have completed the exercise.

+ 18
- 0
exercises/error-handling/build.gradle Просмотреть файл

1
+apply plugin: "java"
2
+apply plugin: "eclipse"
3
+apply plugin: "idea"
4
+
5
+repositories {
6
+  mavenCentral()
7
+}
8
+
9
+dependencies {
10
+  testCompile "junit:junit:4.12"
11
+}
12
+
13
+test {
14
+  testLogging {
15
+    exceptionFormat = 'full'
16
+    events = ["passed", "failed", "skipped"]
17
+  }
18
+}

+ 11
- 0
exercises/error-handling/src/main/java/CustomCheckedException.java Просмотреть файл

1
+class CustomCheckedException extends Exception {
2
+
3
+    CustomCheckedException() {
4
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
5
+    }
6
+
7
+    CustomCheckedException(String message) {
8
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
9
+    }
10
+
11
+}

+ 11
- 0
exercises/error-handling/src/main/java/CustomUncheckedException.java Просмотреть файл

1
+class CustomUncheckedException extends RuntimeException {
2
+
3
+    CustomUncheckedException() {
4
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
5
+    }
6
+
7
+    CustomUncheckedException(String message) {
8
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
9
+    }
10
+
11
+}

+ 49
- 0
exercises/error-handling/src/main/java/ErrorHandling.java Просмотреть файл

1
+import java.util.Optional;
2
+
3
+class ErrorHandling {
4
+
5
+    void handleErrorByThrowingIllegalArgumentException() {
6
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
7
+    }
8
+
9
+    void handleErrorByThrowingIllegalArgumentExceptionWithDetailMessage(String message) {
10
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
11
+    }
12
+
13
+    void handleErrorByThrowingAnyCheckedException() {
14
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
15
+    }
16
+
17
+    void handleErrorByThrowingAnyCheckedExceptionWithDetailMessage(String message) {
18
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
19
+    }
20
+
21
+    void handleErrorByThrowingAnyUncheckedException() {
22
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
23
+    }
24
+
25
+    void handleErrorByThrowingAnyUncheckedExceptionWithDetailMessage(String message) {
26
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
27
+    }
28
+
29
+    void handleErrorByThrowingCustomCheckedException() {
30
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
31
+    }
32
+
33
+    void handleErrorByThrowingCustomCheckedExceptionWithDetailMessage(String message) {
34
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
35
+    }
36
+
37
+    void handleErrorByThrowingCustomUncheckedException() {
38
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
39
+    }
40
+
41
+    void handleErrorByThrowingCustomUncheckedExceptionWithDetailMessage(String message) {
42
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
43
+    }
44
+
45
+    Optional<Integer> handleErrorByReturningOptionalInstance(String integer) {
46
+        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
47
+    }
48
+
49
+}

+ 116
- 0
exercises/error-handling/src/test/java/ErrorHandlingTest.java Просмотреть файл

1
+import org.junit.Before;
2
+import org.junit.Ignore;
3
+import org.junit.Rule;
4
+import org.junit.Test;
5
+import org.junit.rules.ExpectedException;
6
+
7
+import static org.junit.Assert.assertEquals;
8
+import static org.junit.Assert.assertFalse;
9
+import static org.junit.Assert.assertTrue;
10
+
11
+import java.util.Optional;
12
+
13
+public class ErrorHandlingTest {
14
+
15
+    private ErrorHandling errorHandling;
16
+
17
+    @Rule
18
+    public ExpectedException thrown = ExpectedException.none();
19
+
20
+    @Before
21
+    public void setUp() {
22
+        errorHandling = new ErrorHandling();
23
+    }
24
+
25
+    @Test
26
+    public void testThrowIllegalArgumentException() {
27
+        thrown.expect(IllegalArgumentException.class);
28
+        errorHandling.handleErrorByThrowingIllegalArgumentException();
29
+    }
30
+
31
+    @Ignore("Remove to run test")
32
+    @Test
33
+    public void testThrowIllegalArgumentExceptionWithDetailMessage() {
34
+        thrown.expect(IllegalArgumentException.class);
35
+        thrown.expectMessage("This is the detail message.");
36
+        errorHandling.handleErrorByThrowingIllegalArgumentExceptionWithDetailMessage("This is the detail message.");
37
+    }
38
+
39
+    @Ignore("Remove to run test")
40
+    @Test
41
+    public void testThrowAnyCheckedException() {
42
+        try {
43
+            errorHandling.handleErrorByThrowingAnyCheckedException();
44
+        } catch (Exception e) {
45
+            assertFalse(e instanceof RuntimeException);
46
+        }
47
+    }
48
+
49
+    @Ignore("Remove to run test")
50
+    @Test
51
+    public void testThrowAnyCheckedExceptionWithDetailMessage() {
52
+        try {
53
+            errorHandling.handleErrorByThrowingAnyCheckedExceptionWithDetailMessage("This is the detail message.");
54
+        } catch (Exception e) {
55
+            assertFalse(e instanceof RuntimeException);
56
+            assertEquals("This is the detail message.", e.getMessage());
57
+        }
58
+    }
59
+
60
+    @Ignore("Remove to run test")
61
+    @Test
62
+    public void testThrowAnyUncheckedException() {
63
+        thrown.expect(RuntimeException.class);
64
+        errorHandling.handleErrorByThrowingAnyUncheckedException();
65
+    }
66
+
67
+    @Ignore("Remove to run test")
68
+    @Test
69
+    public void testThrowAnyUncheckedExceptionWithDetailMessage() {
70
+        thrown.expect(RuntimeException.class);
71
+        thrown.expectMessage("This is the detail message.");
72
+        errorHandling.handleErrorByThrowingAnyUncheckedExceptionWithDetailMessage("This is the detail message.");
73
+    }
74
+
75
+    @Ignore("Remove to run test")
76
+    @Test
77
+    public void testThrowCustomCheckedException() throws CustomCheckedException {
78
+        thrown.expect(CustomCheckedException.class);
79
+        errorHandling.handleErrorByThrowingCustomCheckedException();
80
+    }
81
+
82
+    @Ignore("Remove to run test")
83
+    @Test
84
+    public void testThrowCustomCheckedExceptionWithDetailMessage() throws CustomCheckedException {
85
+        thrown.expect(CustomCheckedException.class);
86
+        thrown.expectMessage("This is the detail message.");
87
+        errorHandling.handleErrorByThrowingCustomCheckedExceptionWithDetailMessage("This is the detail message.");
88
+    }
89
+
90
+    @Ignore("Remove to run test")
91
+    @Test
92
+    public void testThrowCustomUncheckedException() {
93
+        thrown.expect(CustomUncheckedException.class);
94
+        errorHandling.handleErrorByThrowingCustomUncheckedException();
95
+    }
96
+
97
+    @Ignore("Remove to run test")
98
+    @Test
99
+    public void testThrowCustomUncheckedExceptionWithDetailMessage() {
100
+        thrown.expect(CustomUncheckedException.class);
101
+        thrown.expectMessage("This is the detail message.");
102
+        errorHandling.handleErrorByThrowingCustomUncheckedExceptionWithDetailMessage("This is the detail message.");
103
+    }
104
+
105
+    @Ignore("Remove to run test")
106
+    @Test
107
+    public void testReturnOptionalInstance() {
108
+        Optional<Integer> successfulResult = errorHandling.handleErrorByReturningOptionalInstance("1");
109
+        assertTrue(successfulResult.isPresent());
110
+        assertEquals(1, (int) successfulResult.get());
111
+
112
+        Optional<Integer> failureResult = errorHandling.handleErrorByReturningOptionalInstance("a");
113
+        assertFalse(failureResult.isPresent());
114
+    }
115
+
116
+}

+ 1
- 0
exercises/settings.gradle Просмотреть файл

25
 include 'diamond'
25
 include 'diamond'
26
 include 'difference-of-squares'
26
 include 'difference-of-squares'
27
 include 'diffie-hellman'
27
 include 'diffie-hellman'
28
+include 'error-handling'
28
 include 'etl'
29
 include 'etl'
29
 include 'flatten-array'
30
 include 'flatten-array'
30
 include 'food-chain'
31
 include 'food-chain'