Handling Exceptions in Collections Example

This program demonstrates handling exceptions in Java collections.

Problem Statement

Write a Java program that handles exceptions when accessing invalid elements in a collection.

Source Code

1 import java.util.*;
2 public class CollectionsExceptionExample {
3 public static void main(String[] args) {
4 System.out.println("Eduinq Collections Exception Example");
5 List<String> list=new ArrayList<>();
6 list.add("A"); list.add("B");
7 try {
8 System.out.println(list.get(5));
9 } catch(IndexOutOfBoundsException e) {
10 System.out.println("Eduinq Exception: Invalid Collection Index");
11 }
12 }
13 }

Program Output

					Eduinq Collections Exception Example
Eduinq Exception: Invalid Collection Index
				

Explanation

Collections throw IndexOutOfBoundsException when accessing invalid indices. - Try-catch ensures program continues gracefully. - Provides meaningful error messages for debugging. - In enterprise systems, collection exception handling ensures safe data access. Conclusion: Shows handling exceptions in collections.

Quick Links to Explore