Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

try — exception handling and resource closing

The reserved keyword `try` starts a block associated with exception handling or automatic resource closing. Ordinary `try` requires `catch`, `finally`, or both; `try`-with-resources can omit them.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

try { statements; } catch (ExceptionType e) { handler; }
try { statements; } finally { cleanup; }
try { statements; } catch (ExceptionType e) { handler; } finally { cleanup; }
try (ResourceType resource = initializer) { statements; }

try is a reserved keyword, so it cannot be a variable name. Ordinary try requires at least one catch or a finally block. When an exception is thrown, the first matching catch executes; without a match, the exception propagates. Place more specific exception types before broader ones.

When control leaves the construct, finally executes, including on return or an exception. Avoid return or a new throw there: they can replace the earlier result or exception. Do not treat finally as guaranteed to execute after JVM termination.

try-with-resources uses AutoCloseable resources and can omit catch and finally. It closes initialized, non-null resources in reverse order, before its own catch and finally blocks. If close() throws a different exception instance while a primary exception is already propagating (for example, from the body), the closing exception does not replace the primary one. It is recorded as suppressed and returned by getSuppressed() on the primary exception only if suppression is enabled on that exception. If close() throws the primary exception instance itself, the attempt at self-suppression throws IllegalArgumentException instead, even if suppression is disabled.

Examples

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("start");
            throw new IllegalArgumentException("invalid");
        } catch (IllegalArgumentException e) {
            System.out.println("caught");
        } finally {
            System.out.println("cleanup");
        }
        System.out.println("done");
    }
}

Result

start
caught
cleanup
done

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources