Reading — step 1 of 5
Learn
~1 min readErrors and Optionals
Java has two exception families:
Checked exceptions extend Exception (but not RuntimeException). The compiler forces you to declare or catch them. Examples: IOException, SQLException.
Unchecked exceptions extend RuntimeException. No compiler enforcement. Examples: NullPointerException, IllegalArgumentException, ArrayIndexOutOfBoundsException.
try {
int n = Integer.parseInt(input);
return doSomething(n);
} catch (NumberFormatException e) {
return -1;
} catch (RuntimeException e) {
log(e);
throw e; // re-throw
} finally {
cleanup(); // always runs
}
Multi-catch:
try { ... }
catch (IOException | SQLException e) {
log(e);
}
throws in method signature — for checked exceptions:
String readFile(Path p) throws IOException {
return Files.readString(p);
}
try-with-resources auto-closes anything that implements AutoCloseable:
try (BufferedReader br = Files.newBufferedReader(p)) {
return br.readLine();
}
Custom exceptions:
class ValidationException extends RuntimeException {
public ValidationException(String msg) { super(msg); }
}
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…