Checked exceptions inside a lambda: wrap them
UncheckedIOException(cause) uses cause.toString() as its message. getCause() is typed IOException, so no cast is needed.
Checked exceptions (subclasses of Exception but not RuntimeException) must be caught or declared with throws, and the compiler enforces it. Unchecked exceptions (RuntimeException, Error and their subclasses) need no declaration because they usually mean a bug or a broken environment.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static boolean isChecked(Class<? extends Throwable> c) using RuntimeException.class.isAssignableFrom(c) and Error.class.isAssignableFrom(c). Test it on IOException.class, IllegalStateException.class and OutOfMemoryError.class.
Write a method int parsePositive(String s) that throws an unchecked IllegalArgumentException for a non-positive number and lets NumberFormatException pass through. Call it in main with "7", "-3" and "x", catching each problem and printing its simple class name and message.
Given static int lengthOf(String path) throws IOException { if (path.isEmpty()) throw new IOException("empty path"); return path.length(); }, sum the lengths of List.of("a.txt", "", "bb.txt") with forEach and a wrapping lambda, and print the wrapped message when it fails.
Explain it without notes
What is the difference between checked and unchecked exceptions, and how does Java decide which is which?
What does 'catch or declare' mean, and who enforces it?
When would you design an API to throw a checked exception, and when an unchecked one?
Why do checked exceptions cause trouble with lambdas, and how do you deal with it?
Why can't an overriding method throw a broader checked exception?
Expected output
fetched A
wrapped: java.io.IOException: server refused b
cause: IOException - server refused b