Sobes.tech
Senior

What is multi-catch in Java? What are the limitations and rules?

sobes.tech AI

Answer from AI

Multi-catch in Java is the ability to handle multiple exceptions in a single catch block, listed separated by the vertical bar |. This allows avoiding code duplication when handling different exceptions in the same way.

Rules and restrictions:

  • Exceptions in multi-catch must be incompatible in the hierarchy (you cannot catch an exception and its subclass simultaneously).
  • The exception variable in the catch block is final — it cannot be modified.
  • Syntax:
try {
    // code
} catch (IOException | SQLException ex) {
    // handling for both exceptions
}

This simplifies the code and improves readability, especially when exception handling is the same.

What is multi-catch in Java? What are the limitations… - sobes.tech