Core JAVA

Different Exception Generate in Array in Java(7)

Introduction
In this article we are going to describe the many exceptions that are possibly generated by an array in Java. So now we describe each Exception type in detail one by one. First we give you a little introduction to arrays in Java.

Array Definition 

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. And it also contains similar types of data. Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, the numbering begins with 0.

Possible Error Type

1 – NullPointerException : In Java a NullPointerException is a class which also extends RuntimeException. There are the following conditions where the NullPointerException is generated. They are thrown when an application attempts to use null in a case where an object is required.

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.

2 – NegativeArraySizeException : This error is thrown when anyone wants create an array with a negative size. NegativeArraySizeException is a class in Java which extends RuntimeException.

3 – ArrayIndexOutOfBoundsException : This type of error is generated when an array has been accessed with an illegal index. In other words when an array is accessed by a negative index or more than the size of the array. In Java it’s a separate class and this class extends the IndexOutOfBoundException class.

4 – IndexOutOfBoundsException : This type of exception is thrown by all indexing pattern data types such as an array string and a vector etc., when it is accessed out of the index (range). IndexOutOfBoundException is also a separate class in Java and it extends RuntimeException.

5 – ClassCastException : The ClassCastException is thrown when the following code has attempted to cast an object to a subclass of which it is not an instance. ClassCastException is also a separate class in Java and it extends RuntimeException.

ClassCastException condition:

Object x = new Integer(0);
System.out.println((String)x);

6 – ArrayStoreException : This type of exception is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException. ArrayStoreException is also a separate class in Java and it extends RuntimeException.

For example:

Object x[] = new String[7];
x[0] = new Integer(0);

Example:

public class ExceptionInArray {
 
      public static void main(String[] args) {
            int array[] = null;
            int arraySize = 4;
            int arrayInc = -0;
            int output;
 
            for (int i = 0; i < 6; i++) {
                  try {
                        // Multiple Switch Conditions
                        switch (i) {
                        case 0:
                              output = array[0]; // Generates a NullPointerException.
                              break;
                        case 1:
                              array = new int[arrayInc]; // Generates a
                              // NegativeArraySizeException.
                              output = array[arrayInc];
                              break;
                        case 2:
                              array = new int[arraySize]; // Generate the
                              // ArrayIndexOutOfBoundsException.
                              output = array[arraySize];
                              break;
                        case 3:
                              array = new int[5]; // Generate the
                              // IndexOutOfBoundsException.
                              output = array[5];
                        case 4:
                              Object newArray = new Integer(0); // Generate the
                              // ClassCastException.
                              System.out.println((String) newArray);
                        case 5:
                              Object X[] = new String[-5]; // Generate the
                              // ArrayStoreException.
                              X[0] = new Integer(0);
                              System.out.println(X);
                        }
 
                  } catch (NullPointerException | NegativeArraySizeException | ArrayIndexOutOfBoundsException | ClassCastException | ArrayStoreException ex) {
                        System.out.println("n Exception Generated: "
                                    + ex.getMessage());
                        ex.printStackTrace();
                   } 
            }
      }
}

OUTPUT:

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago