8000 update · githubcs/Java-Coding-Problems@9a7184a · GitHub
[go: up one dir, main page]

Skip to content

Commit 9a7184a

Browse files
committed
update
1 parent 3924360 commit 9a7184a

File tree

1 file changed

+8
-4
lines changed
  • Chapter_13/P262_ThrowingNoSuchElementException/src/modern/challenge

1 file changed

+8
-4
lines changed

Chapter_13/P262_ThrowingNoSuchElementException/src/modern/challenge/Book.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public String findStatusAvoid() {
1414
if (status.isPresent()) {
1515
return status.get();
1616
} else {
17-
throw new NoSuchElementException();
17+
throw new NoSuchElementException("Status cannot be found");
1818
}
1919
}
2020

@@ -24,7 +24,10 @@ public String findStatusPrefer1() {
2424
// fetch an Optional prone to be empty
2525
Optional<String> status = Optional.empty();
2626

27-
return status.orElseThrow(IllegalStateException::new);
27+
return status.orElseThrow(
28+
() -> new IllegalStateException("Status cannot be found"));
29+
// or without message
30+
// return status.orElseThrow(IllegalStateException::new);
2831
}
2932

3033
// Prefer (before Java 10)
@@ -33,7 +36,8 @@ public String findStatusPrefer2() {
3336
// fetch an Optional prone to be empty
3437
Optional<String> status = Optional.empty();
3538

36-
return status.orElseThrow(NoSuchElementException::new);
39+
return status.orElseThrow(
40+
() -> new IllegalStateException("Status cannot be found"));
3741
}
3842

3943
// Prefer (Java 10+)
@@ -42,6 +46,6 @@ public String findStatusPrefer3() {
4246
// fetch an Optional prone to be empty
4347
Optional<String> status = Optional.empty();
4448

45-
return status.orElseThrow(); // NoSuchElementException
49+
return status.orElseThrow(); // NoSuchElementException
4650
}
4751
}

0 commit comments

Comments
 (0)
0