- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Nested try blocks in Exception Handling in Java
As the name suggests, a try block within a try block is called nested try block in Java. This is needed when different blocks like outer and inner may cause different errors. To handle them, we need nested try blocks.
Let us now see an example to implement nested try blocks −
Example
class Main { // main method public static void main(String args[]) { try { int a[]=new int[10]; // displaying element at index 12 System.out.println(a[12]); // another try block try { System.out.println("Division"); int res = 100/ 0; } catch (ArithmeticException ex2) { System.out.println("Sorry! Division by zero isn't feasible!"); } } catch (ArrayIndexOutOfBoundsException ex1) { System.out.println("ArrayIndexOutOfBoundsException"); } } }
Output
ArrayIndexOutOfBoundsException
Now we will do some changes in the above example −
Example
class Main { // main method public static void main(String args[]) { try { int a[] = {30, 45, 60, 75, 90, 105, 120, 140, 160, 200}; // displaying element at index 8 System.out.println("Element at index 8 = "+a[8]); // another try block try { System.out.println("Division"); int res = 100/ 0; } catch (ArithmeticException ex2) { System.out.println("Sorry! Division by zero isn't feasible!"); } } catch (ArrayIndexOutOfBoundsException ex1) { System.out.println("ArrayIndexOutOfBoundsException"); } } }
Output
Element at index 8 = 160 Division Sorry! Division by zero isn't feasible!
- Related Articles
- PHP Exception Handling with Multiple catch blocks
- What are try, catch, finally blocks in Java?
- Exception Handling in C++ vs Java
- Exception handling with method overriding in Java.
- Can a try block have multiple catch blocks in Java?
- Comparison of Exception Handling in C++ and Java
- Exception handling in PowerShell
- Can we define a try block with multiple catch blocks in Java?
- How to use Try/catch blocks in C#?
- Exception Handling Basics in C++
- Can we write any statements between try, catch and finally blocks in Java?
- What is exception handling in C#?
- What is Exception Handling in PHP ?
- What is exception handling in Python?
- NodeJS - Exception Handling in Asynchronous Code

Advertisements