Java SE 17 (1Z0-829) study materials
Java SE 17 (1Z0-829) study resources

Java SE 17 (1Z0-829): Handling exceptions and using local variable type inference

Java SE 17 (1Z0-829) · Work through your exam, one topic at a time.

All guide sections

Handling exceptions and using local variable type inference

Exception categories

Throwable has Error and Exception branches. RuntimeException and its subclasses are unchecked; checked exceptions must be caught or declared. Overriding methods may throw fewer or narrower checked exceptions, never broader ones. finally always runs except for System.exit or a JVM crash, and a return in finally discards a prior return.

try-with-resources

Resources must implement AutoCloseable and are closed in reverse declaration order. If the body throws and close also throws, the close exception is suppressed on the primary exception; retrieve it with getSuppressed(). Multi-catch cannot include related types, and the parameter is implicitly final.

Worked example

try (var a = new R("a"); var b = new R("b")) { throw new RuntimeException("body"); } catch (Exception e) { /* handle */ } b closes before a. The RuntimeException from the body is primary; any close exception is suppressed.

var rules

var is for local variables, for-loop variables, try-with-resources, and lambda parameters. It requires an initializer with a determinable type, so var x = null; fails, as do var a = 1, b = 2; and var x = {1,2};. var is not allowed for fields, method parameters, return types, or constructor parameters. It is not a keyword and does not make Java dynamically typed.

Traps

Catching Exception catches checked and unchecked exceptions but not Error. A catch for a checked exception that cannot be thrown is a compile error unless the try can throw it. Do not confuse throws (declaration) with throw (statement).