
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Throw Exception Without Breaking For Loop in Java
Whenever an exception occurred in a loop the control gets out of the loop, by handling the exception the statements after the catch block in the method will get executed. But, the loop breaks.
Example
public class ExceptionInLoop{ public static void sampleMethod(){ String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"}; try { for(int i=0; i<=10; i++) { System.out.println(str[i]); System.out.println(i); } }catch (ArrayIndexOutOfBoundsException ex){ System.out.println("Exception occurred"); } System.out.println("hello"); } public static void main(String args[]) { sampleMethod(); } }
Output
Mango 0 Apple 1 Banana 2 Grapes 3 Oranges 4 Exception occurred Hello
One way to execute the loop without breaking is to move the code that causes the exception to another method that handles the exception.
If you have try catch within the loop it gets executed completely inspite of exceptions.
Example
public class ExceptionInLoop{ public static void print(String str) { System.out.println(str); } public static void sampleMethod()throws ArrayIndexOutOfBoundsException { String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"}; for(int i=0; i<=10; i++) { try { print(str[i]); System.out.println(i); } catch(Exception e){ System.out.println(i); } } } public static void main(String args[]) { try{ sampleMethod(); }catch(ArrayIndexOutOfBoundsException e) { System.out.println(""); } } }
Output
Mango 0 Apple 1 Banana 2 Grapes 3 Oranges 4 5 6 7 8 9 10
Advertisements