Lesson content
Read, practise, then check your understanding
Checked exceptions must be caught or declared with throws; runtime exceptions and errors are unchecked. Throw specific meaningful exceptions and catch the most specific types before general ones.
Safe boundaries
static int parsePositive(String text) {
try {
int value = Integer.parseInt(text);
if (value <= 0) throw new IllegalArgumentException("positive required");
return value;
} catch (NumberFormatException error) {
throw new IllegalArgumentException("invalid integer", error);
} finally {
// unconditional follow-up; not usually resource closing
}
}
Preserve the cause when translating exceptions. Avoid empty catches and broad catch (Exception) except at an application boundary. finally normally runs even after return, but try-with-resources is safer for closing. Multiple resources close in reverse order and suppressed exceptions remain inspectable. Use exceptions for exceptional failure, not ordinary optional outcomes; validate early and document checked failure contracts.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.