← Back to Home

try-catch

The try-catch construct in Java is used to handle runtime exceptions gracefully, preventing abnormal program termination and allowing controlled recovery.

This is a fundamental and high-frequency interview topic in Java exception handling.

What Is try-catch?

  • Used to detect and handle exceptions
  • Separates normal logic from error-handling logic
  • Prevents program crash
  • Enables meaningful error recovery or messaging

Basic Syntax

try {
    // risky code
} catch (ExceptionType e) {
    // handling code
}
          

How try-catch Works (Execution Flow)

  1. Code inside try executes normally
  2. If no exception → catch is skipped
  3. If exception occurs:
    • JVM creates an exception object
    • Control jumps to the matching catch
  4. Remaining code executes normally after handling

Basic Example

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}
          

Output:

Cannot divide by zero
          

Result: ✔ Program continues execution

Syntax Rules (Very Important)

1. try Must Be Followed by catch or finally

try {
    // code
} catch (Exception e) {
    // handling
}
          

✔ Valid

❌ Invalid:

try {
    // code
}
          

2. Code Inside try Must Be Exception-Prone

try {
    System.out.println("Hello");
}
          

✔ Compiles

⚠️ But meaningless if no risk exists

Multiple catch Blocks

Used when multiple exceptions may occur.

try {
    int[] arr = new int[3];
    System.out.println(arr[5]);
} catch (ArithmeticException e) {
    System.out.println("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index error");
}
          

✔ First matching catch is executed

Catch Block Ordering Rule (Interview Favorite)

Child exception must come before parent exception

❌ Invalid:

catch (Exception e) { }
catch (ArithmeticException e) { } // unreachable
          

✅ Valid:

catch (ArithmeticException e) { }
catch (Exception e) { }
          

Using Exception Object (e)

catch (Exception e) {
    System.out.println(e.getMessage());
}
          

Common methods:

  • getMessage()
  • printStackTrace()
  • toString()

Single catch with Multiple Exceptions (Java 7+)

try {
    // risky code
} catch (ArithmeticException | NullPointerException e) {
    System.out.println("Handled");
}
          
  • ✔ Reduces code duplication
  • ✔ Exceptions must be unrelated (no inheritance)

Nested try-catch

try {
    try {
        int x = 10 / 0;
    } catch (ArithmeticException e) {
        System.out.println("Inner catch");
    }
} catch (Exception e) {
    System.out.println("Outer catch");
}
          

✔ Useful for fine-grained handling

try-catch Without finally

Allowed when cleanup is not required.

try {
    int x = 10 / 2;
} catch (Exception e) {
    System.out.println("Error");
}
          

Common Beginner Mistakes

  • Catching generic Exception unnecessarily
  • Empty catch blocks
  • Incorrect catch order
  • Overusing nested try-catch
  • Swallowing exceptions without logging

Best Practices (Real-World)

  • Catch specific exceptions
  • Log exceptions properly
  • Do not use exceptions for flow control
  • Avoid empty catch blocks
  • Keep try block minimal

Interview-Ready Answers

Short Answer

try-catch is used to handle exceptions and prevent abnormal termination of a program.

Detailed Answer

In Java, the try block contains code that may throw an exception, and the catch block handles the exception. When an exception occurs, control is transferred to the matching catch block, allowing the program to continue execution gracefully.

Key Takeaway

try-catch separates normal logic from error handling. Proper use ensures stable, readable, and fault-tolerant Java applications.