NegativeArraySizeException in java

NegativeArraySizeException class is available in java.lang package and it extends RuntimeException class. It is an unchecked exception.


public class NegativeArraySizeException extends RuntimeException


NegativeArraySizeException class inherits methods from java.lang.Object class and java.lang.Throwable class.

Hierarchy of ClassCastException


Object => Throwable => Exception => RuntimeException => NegativeArraySizeException

When NegativeArraySizeException Occurs


NegativeArraySizeException occurs whenever an application tries to create an array with negative size.

For example, whenever we assigned the negative size to an array.
int[ ] arr=new int[-10]; , Here the array size is -10 i.e., negative size. Let’s we check in the program.

Example:



package com.exceptions;
public class NASExceptionTest {
       public static void main(String[] args) {
              int[] arr=new int[-10];
       }
}


Output:



Exception in thread "main" java.lang.NegativeArraySizeException
       at com.exceptions.NASExceptionTest.main(NASExceptionTest.java:4)



Here JVM has thrown NegativeArraySizeException because we created an array with negative size as shown in the program.


No comments:

Post a Comment