Skip to main content
Core Java Intermediate Practical Coding Topic: Exceptions & Resource Safety

How does exception handling and try-with-resources work in Java?

Quick Summary: Java divides Throwable into Error, checked Exception (enforced by compiler), and unchecked RuntimeException; try-with-resources automatically closes AutoCloseable resources cleanly even if exceptions occur in the body or close().

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

Direct Interview Answer

All exceptions descend from Throwable. Checked exceptions (like IOException, SQLException) inherit directly from Exception and must be caught or declared in throws. Unchecked exceptions inherit from RuntimeException and signal programming or unrecoverable business violations.

With try (Resource r = ...), any object implementing AutoCloseable has its close() invoked automatically in reverse declaration order, preserving primary exceptions while attaching secondary close failures via addSuppressed().

Detailed Technical Explanation

Before Java 7, closing streams inside a finally block risked masking the real business exception if close() also threw an exception. try-with-resources solves that cleanly: the primary exception from the try block stays the root exception, and close errors are attached to Throwable.getSuppressed().

Practical Walkthrough

Custom resource implementing AutoCloseable shows deterministic reverse close order.

Code Example — JAVA
class DbConnection implements AutoCloseable {
    public void query() { System.out.println("Executing SQL query"); }
    @Override
    public void close() { System.out.println("Connection safely closed"); }
}

public class ResourceSafetyDemo {
    public static void main(String[] args) {
        try (DbConnection conn = new DbConnection()) {
            conn.query();
        }
    }
}
Expected Output / Verification
Executing SQL query
Connection safely closed

Real-World Production Use Case

Managing JDBC Connections, PreparedStatements, BufferedReaders, and HTTP input streams in enterprise services without leaking file descriptors or connection pool slots.

Common Interview Mistakes to Avoid

  • Swallowing exceptions in empty catch (Exception e) {} blocks without logging or rethrowing context.
  • Returning inside a finally block, which silently discards exceptions thrown inside try/catch.
  • Catching broad Throwable instead of specific domain exceptions.
Topics: #core-java #exceptions #try-with-resources #autocloseable
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.