Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

The catch clause

The catch clause: A catch clause handles an exception thrown from its associated try when the exception’s run-time type is assignable to the declared catch parameter type.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

catch

A catch clause handles an exception thrown from its associated try when the exception’s run-time type is assignable to the declared catch parameter type.

Catch the narrowest exception you can meaningfully handle, add context or restore interruption, and let unhandled failures propagate.

A broader catch cannot precede a narrower one, an empty catch hides failures, and catching Exception does not include Error or other Throwable branches.

Multi-catch separates alternatives with | and gives an effectively final parameter; try-with-resources attaches a close failure as suppressed on the body exception.

The first catch prints number; the second preserves primary=body and reads the close failure as suppressed=close.

Examples

import java.io.IOException;
public class Main {
  static final class Broken implements AutoCloseable { public void close() throws IOException {throw new IOException("close");} }
  public static void main(String[] args){
    try { Integer.parseInt("x"); } catch(NumberFormatException ex){System.out.println("number");}
    try(var ignored=new Broken()){throw new IllegalStateException("body");}catch(Exception ex){System.out.println("primary="+ex.getMessage());System.out.println("suppressed="+ex.getSuppressed()[0].getMessage());}
  }
}

Result

number
primary=body
suppressed=close

The first catch prints number; the second preserves primary=body and reads the close failure as suppressed=close.

Sources