Java Notes
Complete guide to try-catch blocks in Java covering syntax, multiple catch blocks, nested try, multi-catch (Java 7+), exception propagation, and practical examples with output.
What is a Try-Catch Block?
The try-catch block is the fundamental mechanism for handling exceptions in Java. Code that might throw an exception is placed inside the try block, and the code to handle the exception is placed inside the catch block.
Basic Syntax
try {
// Code that may throw an exception
// (risky/suspicious code)
} catch (ExceptionType variableName) {
// Code to handle the exception
// (recovery/error reporting code)
}How It Works — Step by Step
Basic Try-Catch Example
public class BasicTryCatch {
public static void main(String[] args) {
System.out.println("=== Program Start ===");
try {
System.out.println("Inside try: before exception");
int result = 100 / 0; // ArithmeticException
System.out.println("Inside try: after exception (NEVER prints)");
} catch (ArithmeticException e) {
System.out.println("Inside catch: " + e.getMessage());
}
System.out.println("=== Program continues normally ===");
}
}Output:
Key Insight: When an exception occurs in the try block, the remaining statements in the try block are SKIPPED, and control immediately transfers to the matching catch block.
Multiple Catch Blocks
You can have multiple catch blocks to handle different types of exceptions differently:
Output:
Rule: Order Matters — Specific to General
// ❌ COMPILE ERROR: Unreachable catch block
try {
// code
} catch (Exception e) { // Parent class first
// This catches everything
} catch (IOException e) { // ERROR! Already caught above
// Unreachable
}
// ✅ CORRECT: Child exceptions first, parent last
try {
// code
} catch (FileNotFoundException e) { // Most specific first
System.out.println("File not found");
} catch (IOException e) { // Parent of FileNotFoundException
System.out.println("IO error");
} catch (Exception e) { // Most general LAST
System.out.println("Something went wrong");
}Multi-Catch Block (Java 7+)
Java 7 introduced the ability to catch multiple exception types in a single catch block using the pipe (|) operator:
import java.io.IOException;
import java.sql.SQLException;
public class MultiCatchExample {
public static void main(String[] args) {
try {
// Simulating different exceptions
String input = "abc";
int number = Integer.parseInt(input);
} catch (NumberFormatException | ArithmeticException |
ArrayIndexOutOfBoundsException e) {
// Single handler for multiple exception types
System.out.println("Error type: " + e.getClass().getSimpleName());
System.out.println("Message: " + e.getMessage());
}
}
}Output:
Multi-Catch Rules:
- Exception types must NOT be related (no parent-child)
- The catch parameter is implicitly
final(cannot reassigne) - Use
|(pipe) to separate exception types
// ❌ WRONG: IOException is parent of FileNotFoundException
catch (IOException | FileNotFoundException e) { } // Compile error
// ✅ CORRECT: Unrelated exception types
catch (IOException | NumberFormatException e) { }
// ❌ WRONG: Cannot reassign in multi-catch
catch (IOException | SQLException e) {
e = new IOException(); // Compile error - e is final
}Nested Try-Catch Blocks
You can nest try-catch blocks when different parts of your code require different exception handling:
Output:
| Outer try | start |
| Inner try | start |
| Inner catch | Index 5 out of bounds for length 3 |
| Outer try | after inner try-catch |
| Outer catch | / by zero |
When Inner Catch Doesn't Handle the Exception
If the inner catch block doesn't match the exception type, it propagates to the outer catch:
public class ExceptionPropagation {
public static void main(String[] args) {
try {
System.out.println("Outer try");
try {
System.out.println(" Inner try");
int result = 10 / 0; // ArithmeticException
} catch (NullPointerException e) {
// This won't catch ArithmeticException
System.out.println(" Inner catch: " + e);
}
System.out.println("Outer try: after inner (won't print)");
} catch (ArithmeticException e) {
System.out.println("Outer catch handles it: " + e.getMessage());
}
}
}Output:
The Catch Block — What You Can Do With the Exception Object
The exception object (e) provides useful methods:
public class ExceptionMethods {
public static void main(String[] args) {
try {
methodA();
} catch (ArithmeticException e) {
// 1. Get the error message
System.out.println("getMessage(): " + e.getMessage());
// 2. Get exception class and message
System.out.println("toString(): " + e.toString());
// 3. Print full stack trace
System.out.println("\nprintStackTrace():");
e.printStackTrace();
// 4. Get stack trace as array
System.out.println("\nStack trace elements:");
StackTraceElement[] trace = e.getStackTrace();
for (StackTraceElement element : trace) {
System.out.println(" Class: " + element.getClassName()
+ " | Method: " + element.getMethodName()
+ " | Line: " + element.getLineNumber());
}
}
}
static void methodA() {
methodB();
}
static void methodB() {
int result = 10 / 0;
}
}Output:
| getMessage() | / by zero |
| toString() | java.lang.ArithmeticException: / by zero |
| java.lang.ArithmeticException | / by zero |
| at ExceptionMethods.methodB(ExceptionMethods.java | 33) |
| at ExceptionMethods.methodA(ExceptionMethods.java | 29) |
| at ExceptionMethods.main(ExceptionMethods.java | 5) |
| Class | ExceptionMethods | Method: methodB | Line: 33 |
| Class | ExceptionMethods | Method: methodA | Line: 29 |
| Class | ExceptionMethods | Method: main | Line: 5 |
Real-World Example: User Input Validation
Enter your age: abc Error: Please enter a valid number! Enter your age: 25 You are 25 years old. Eligible to vote: Yes
Sample Run:
| Enter your age | abc |
| Error | Please enter a valid number! |
| Enter your age | -5 |
| Error | Age must be between 0 and 150 |
| Enter your age | 25 |
| Your age | 25 |
Real-World Example: Array Processing
Output:
| Array | [10, 20, 30, 40, 50] |
| Index 0 | Value: 10 ✓ |
| Index 2 | Value: 30 ✓ |
| Index 4 | Value: 50 ✓ |
| Index 7 | INVALID (skipped) ✗ |
| Index -1 | INVALID (skipped) ✗ |
| Index 3 | Value: 40 ✓ |
| Valid accesses | 4/6 |
| Sum of valid values | 130 |
Try Without Catch (Try-Finally)
You can have a try block without a catch block, but it MUST have a finally block:
public class TryFinally {
public static void main(String[] args) {
try {
System.out.println("In try block");
// If exception occurs here, it propagates up
// but finally still executes
} finally {
System.out.println("Finally always runs");
}
// Note: No catch block! Exception (if any) propagates to caller
}
}In try block Finally always runs Note: Exception propagates to caller!
Common Mistakes with Try-Catch
1. Catching Exception Too Broadly
2. Try Block Too Large
// ❌ BAD: Entire method in one try block
try {
connectToDatabase();
readUserInput();
processData();
writeResults();
sendEmail();
} catch (Exception e) {
System.out.println("Something went wrong somewhere...");
}
// ✅ GOOD: Separate concerns
try {
connectToDatabase();
} catch (SQLException e) {
System.out.println("Database connection failed");
return;
}
try {
processData();
writeResults();
} catch (IOException e) {
System.out.println("File operation failed: " + e.getMessage());
}3. Unreachable Code After Try-Catch
public class UnreachableCode {
public static void main(String[] args) {
try {
System.out.println("Try block");
return; // Method returns here
} catch (Exception e) {
System.out.println("Catch block");
return; // OR returns here
}
// ❌ COMPILE ERROR: Unreachable statement
// System.out.println("After try-catch");
}
}Try block Catch block Finally block Program continues
Performance Considerations
Output (approximate):
| Try-catch (no exception) | 15 ms |
| Pre-validation | 850 ms |
| Note | Try-catch with NO exception thrown has minimal overhead. |
Key Takeaway: The try block itself has negligible overhead. The cost comes from actually *throwing and catching* exceptions (creating stack traces, unwinding the stack). So don't use exceptions for normal flow control.
Interview Questions
Q1: Can we have a try block without a catch block?
Answer: Yes, but it must be followed by a finally block. A try block alone without both catch and finally will cause a compilation error.
Q2: What happens if an exception occurs in the catch block?
Answer: It propagates normally like any other exception. If there's an outer try-catch that matches, it gets caught there. Otherwise, the default exception handler terminates the program.
Q3: Can we have multiple catch blocks for a single try?
Answer: Yes. You can have any number of catch blocks. They are evaluated top-to-bottom, and the first matching one executes. Child exception types must appear before parent types.
Q4: What is the difference between multi-catch (|) and multiple catch blocks?
Answer: Multi-catch (Java 7+) handles different exception types with the same code: catch (IOException | SQLException e). Multiple separate catch blocks let you handle each type differently. In multi-catch, the parameter is implicitly final and exception types must not be related by inheritance.
Q5: Is there a performance penalty for using try-catch?
Answer: Entering a try block has negligible overhead. The expensive part is when an exception is actually thrown — creating the exception object, capturing the stack trace, and unwinding the call stack. That's why exceptions should not be used for normal program flow.
Q6: What is unreachable catch block error?
Answer: If you catch a parent exception before a child exception, the child catch becomes unreachable because the parent already catches it. The compiler detects this and throws an error.
Q7: What is the difference between throw and catch?
A: throw is used to explicitly create and throw an exception object: throw new IllegalArgumentException("msg"). catch is used to handle (receive) an exception that was thrown. Throw generates the exception; catch handles it. They work together — one method throws, another (or the same) catches.
Q8: Can a try block have zero catch blocks?
A: Yes, if it has a finally block: try { ... } finally { ... }. This pattern is used when you want to guarantee cleanup code runs regardless of exceptions, without actually handling the exception (it propagates to the caller).
Q9: What is exception chaining?
A: Wrapping a caught exception as the cause of a new exception: throw new ServiceException("Failed", originalException). The original exception is preserved via getCause(). This maintains the root cause information while converting low-level exceptions to application-level exceptions.
Q10: How do you handle multiple exception types with the same code?
A: Use multi-catch (Java 7+): catch (IOException | SQLException e) { ... }. The exception variable is implicitly final. Exception types must NOT be related by inheritance (parent catches child anyway). This reduces code duplication when handling is identical.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Try-Catch Block in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, exception, handling, try
Related Java Master Course Topics