1. Introduction
The try-catch construct is the core mechanism Java provides for handling exceptions. Code that might throw an exception is placed inside a try block, and code that handles a specific exception type is placed inside one or more catch blocks that follow it.
Cricket analogy: The try block is like a batsman facing a risky yorker; the catch block is the specific plan, say a defensive block, prepared in advance for exactly that kind of delivery.
Java also supports multiple catch blocks for handling different exception types differently, a multi-catch syntax for combining handlers, and try-with-resources for automatically closing resources like files and database connections.
Cricket analogy: A captain plans separate responses for a rain delay versus a bad-light stoppage (multiple catch blocks), a combined response for either minor stoppage (multi-catch), and an auto-covering-of-the-pitch system that activates without manual action (try-with-resources).
2. Syntax
try {
// risky code
} catch (SpecificException e) {
// handle specific exception
} catch (MoreGeneralException e) {
// handle more general exception
}
// Multi-catch
try {
// risky code
} catch (IOException | SQLException e) {
// handle either type
}
// try-with-resources
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// use br
} catch (IOException e) {
// handle exception
}3. Explanation
When an exception occurs inside a try block, Java looks for the first catch block whose exception type matches (or is a superclass of) the thrown exception, executes it, and skips the rest of the try block. You can chain multiple catch blocks to handle different exception types with different logic — order matters here.
Cricket analogy: Java checks catch blocks top-down like an umpire checking the most specific rule first, a no-ball, before a general rule like illegal delivery; once the first matching rule applies, the rest of the over's other checks are skipped.
Java 7 introduced multi-catch (catch (TypeA | TypeB e)) to avoid duplicating identical handling code for unrelated exception types, and try-with-resources, which automatically closes any resource implementing AutoCloseable once the try block finishes, without needing an explicit finally block.
Cricket analogy: Multi-catch is like a single response plan covering both a "wide" and a "no-ball" without writing duplicate rules for each, and try-with-resources is like the ground staff automatically rolling up the covers once play ends, without a groundskeeper needing to remember.
Exam trap: catch blocks must be ordered from most specific to most general. If you catch a broader exception type (like Exception) before a narrower one (like ArithmeticException), the code will not compile — Java flags the narrower catch as unreachable.
4. Example
public class TryCatchDemo {
public static void main(String[] args) {
int[] data = {1, 2, 3};
try {
int result = 10 / 0;
System.out.println(data[5]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error: " + e.getMessage());
} catch (Exception e) {
System.out.println("General error: " + e.getMessage());
}
System.out.println("Execution continues after handling.");
}
}5. Output
Arithmetic error: / by zero
Execution continues after handling.6. Key Takeaways
- try encloses risky code; catch handles a specific exception type thrown from that try block.
- Multiple catch blocks must be ordered from most specific to most general, or the code fails to compile.
- Multi-catch syntax catch (TypeA | TypeB e) lets one block handle multiple unrelated exception types.
- try-with-resources automatically closes AutoCloseable resources without needing an explicit finally block.
- Only the first matching catch block executes; the rest are skipped.
Practice what you learned
1. What happens if you place a catch(Exception e) block before catch(ArithmeticException e)?
2. What is the correct syntax for a multi-catch block introduced in Java 7?
3. What must a resource implement to be used in a try-with-resources statement?
4. If a try block throws an ArithmeticException and only a catch(NullPointerException e) block exists, what happens?
5. How many catch blocks execute for a single exception thrown in a try block?
Was this page helpful?
You May Also Like
Exceptions in Java
Understand what exceptions are in Java, how the Throwable hierarchy is organized, and why exception handling keeps programs robust.
finally Block in Java
Learn how the finally block guarantees cleanup code execution in Java, even when exceptions or return statements are involved.
Checked vs Unchecked Exceptions in Java
Compare checked and unchecked exceptions in Java, including compiler enforcement, typical use cases, and common exam pitfalls.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics