Java / Java 21 Coding Standards Interview Questions
How is exception handling standardized in Java 21 with multi-catch and try-with-resources?
Multi-catch lets a single catch block handle several unrelated exception types with identical recovery logic, avoiding duplicated catch blocks that differ only in the exception type they name.
try (Connection conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) { ps.executeUpdate(); } catch (SQLException | IllegalStateException e) { log.error("query failed", e); throw new DataAccessException(e); }
Try-with-resources standardizes that any AutoCloseable resource - connections, statements, streams, locks acquired via Lock.lock() wrapped in a closeable adapter - is declared in the parentheses of the try so it is closed automatically, in reverse order of declaration, even if an exception is thrown mid-block.
The combined standard is: never catch an exception without either handling it meaningfully or wrapping and rethrowing it with context, and never manage a closeable resource with a manual finally block when try-with-resources can express the same guarantee more concisely and correctly.
More Related questions...