Nested try statements

 In Java, nested try statements refer to placing one try-catch block inside another try block. This is useful when:

  • You want to handle inner-specific exceptions separately from outer-level exceptions.

  • You have complex logic that may fail at multiple levels.


Syntax of Nested try Blocks


try { // Outer try block try { // Inner try block } catch (ExceptionType1 e) { // Handle inner exception } } catch (ExceptionType2 e) { // Handle outer exception }

πŸ“˜ Example: Nested try-catch


public class NestedTryExample {
public static void main(String[] args) {
try {
// Outer try block
int[] arr = {10, 20, 30};
try {
// Inner try block
int result = arr[2] / 0; // ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException ae) {
System.out.println("Inner Catch: Arithmetic Error - " + ae.getMessage());
}
// Another potential error
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException aioobe) {
System.out.println("Outer Catch: Array Index Error - " + aioobe.getMessage());
}
} }

πŸ’‘ Output:


Inner Catch: Arithmetic Error - / by zero Outer Catch: Array Index Error - Index 5 out of bounds for length 3

πŸ”„ How it works:

  1. The inner try block throws an ArithmeticException → caught by inner catch.

  2. Execution resumes in outer block and encounters arr[5] → throws ArrayIndexOutOfBoundsException → caught by outer catch.


Why use nested try blocks?

  • Handle different exceptions in different scopes.

  • Encapsulate exception-prone operations independently.

  • Maintain clean, modular error handling in large programs.


⚠️ Notes:

  • You can nest multiple levels of try-catch, but keep it readable.

  • Only use nested try when necessary; avoid deep nesting

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism