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)
- Code inside try executes normally
- If no exception → catch is skipped
-
If exception occurs:
- JVM creates an exception object
- Control jumps to the matching catch
- 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.
try-catch Examples (with Output)
1. Simple try-catch
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception caught");
}
}
}
Output
Arithmetic exception caught
2. try Without Exception
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 2;
System.out.println("No error");
} catch (Exception e) {
System.out.println("Error");
}
}
}
Output
No error
3. Multiple catch Blocks
class Demo {
public static void main(String[] args) {
try {
String s = null;
System.out.println(s.length());
} catch (ArithmeticException e) {
System.out.println("Arithmetic");
} catch (NullPointerException e) {
System.out.println("Null pointer");
}
}
}
Output
Null pointer
4. Correct Catch Order (Specific → General)
class Demo {
public static void main(String[] args) {
try {
int[] a = new int[2];
a[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array issue");
} catch (Exception e) {
System.out.println("General issue");
}
}
}
Output
Array issue
5. Wrong Catch Order (Compile-Time Error)
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
}
// catch (Exception e) {}
// catch (ArithmeticException e) {} // ❌ unreachable
}
}
Explanation
Parent exception must be last
6. Single catch for Multiple Exceptions (Java 7+)
class Demo {
public static void main(String[] args) {
try {
int[] a = new int[2];
a[3] = 5;
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("Array or Null issue");
}
}
}
Output
Array or Null issue
7. Nested try-catch
class Demo {
public static void main(String[] args) {
try {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Inner catch");
}
} catch (Exception e) {
System.out.println("Outer catch");
}
}
}
Output
Inner catch
8. try-catch-finally Flow
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println("Catch");
} finally {
System.out.println("Finally");
}
}
}
Output
Catch
Finally
9. finally Executes Without Exception
class Demo {
public static void main(String[] args) {
try {
System.out.println("Try");
} catch (Exception e) {
System.out.println("Catch");
} finally {
System.out.println("Finally");
}
}
}
Output
Try
Finally
10. finally with return
class Demo {
static int test() {
try {
return 10;
} catch (Exception e) {
return 20;
} finally {
return 30;
}
}
public static void main(String[] args) {
System.out.println(test());
}
}
Output
30
11. Exception Propagation to Caller
class Demo {
static void m1() {
m2();
}
static void m2() {
int a = 10 / 0;
}
public static void main(String[] args) {
try {
m1();
} catch (Exception e) {
System.out.println("Handled in main");
}
}
}
Output
Handled in main
12. Catching Parent Exception
class Demo {
public static void main(String[] args) {
try {
String s = null;
s.length();
} catch (Exception e) {
System.out.println("Exception caught");
}
}
}
Output
Exception caught
13. Rethrowing Exception
class Demo {
static void test() {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Handled");
throw e;
}
}
public static void main(String[] args) {
try {
test();
} catch (Exception e) {
System.out.println("Rethrown");
}
}
}
Output
Handled
Rethrown
14. Exception Object Methods
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Output
/ by zero
15. printStackTrace()
class Demo {
public static void main(String[] args) {
try {
String s = null;
s.length();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation
Prints exception name, message, and call stack
16. Catch Block Without Exception Occurring
class Demo {
public static void main(String[] args) {
try {
System.out.println("Safe code");
} catch (Exception e) {
System.out.println("Catch");
}
}
}
Output
Safe code
17. Try-Catch in Loop
class Demo {
public static void main(String[] args) {
int[] a = {10, 20};
for (int i = 0; i <= a.length; i++) {
try {
System.out.println(a[i]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index error");
}
}
}
}
Output
10
20
Index error
18. Catching Specific vs Generic Exception
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Specific catch");
}
}
}
Output
Specific catch
19. try Cannot Exist Alone
class Demo {
public static void main(String[] args) {
// try { int a = 10; } // ❌ invalid
}
}
Explanation
try must be followed by catch or finally
20. Interview Summary – try-catch
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println("Handled");
}
System.out.println("Program continues");
}
}
Key Points
- Prevents abnormal termination
- Catch order matters
- finally usually executes
- Supports graceful error handling
Output
Handled
Program continues