Two kinds of exceptions
- Checked exceptions (IOException, SQLException) extend Exception. The compiler forces you to catch them or declare them with throws. They describe problems outside your control, such as a missing file.
- Unchecked exceptions (NullPointerException, IllegalArgumentException, ArrayIndexOutOfBoundsException) extend RuntimeException. They usually mean a bug or bad input, and the compiler does not force you to handle them.
- Errors such as OutOfMemoryError are serious problems that applications normally should not catch.
The order things run in
public class Resources {
static class Res implements AutoCloseable {
final String n;
Res(String n) { this.n = n; System.out.println("open " + n); }
public void close() { System.out.println("close " + n); }
}
static int parseMarks(String s) {
try {
int m = Integer.parseInt(s);
if (m < 0 || m > 100) throw new IllegalArgumentException("out of range: " + m);
return m;
} catch (NumberFormatException e) {
System.out.println("not a number: " + s);
return -1;
} finally {
System.out.println("checked " + s);
}
}
public static void main(String[] args) {
try (Res a = new Res("A"); Res b = new Res("B")) {
System.out.println("working");
}
System.out.println(parseMarks("87"));
System.out.println(parseMarks("8x"));
try { parseMarks("120"); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
}
}open A
open B
working
close B
close A
checked 87
87
not a number: 8x
checked 8x
-1
checked 120
out of range: 120What to take from it
- try-with-resources closes every resource automatically, in reverse order of opening, even when an exception is thrown. Use it for files, streams, scanners and JDBC connections instead of closing them by hand in finally.
- finally runs whether the try block returns normally, the exception is caught, or it escapes to the caller.
- Catch the most specific exception you can handle. Catching Exception everywhere hides bugs.
- Never leave a catch block empty. At least log the problem, or rethrow it wrapped with context.
#java#exceptions#try-with-resources#error handling
Sources and further reading
Practise this as an interview question
Written by the UniCircle team, checked by an editor on 22 Oct 2026. It is not official policy of any university. Exam patterns and rules change; confirm dates and rules on the official website.
