Open In App

How to Handle a java.lang.NegativeArraySizeException in Java?

In Java, NegativeArraySizeException is the pre-defined class that can be used to represent the unchecked exception. It is a subclass of the java.lang package, and it can be used to identify that an array was attempted to be created with a negative size, which is not allowed in Java.

In this article, we will learn how to handle a java.lang.NegativeArraySizeException in Java.

Step-by-step Implementation:

Program to Handle a java.lang.NegativeArraySizeException in Java




// Java Program to  handle a NegativeArraySizeException 
import java.lang.Exception;
import java.lang.NegativeArraySizeException;
  
// Driver Class
public class GfGNegativeArraySize {
      // Main Function
    public static void main(String args[]) 
    {
        try {
            int size = -5;
               // Attempting to create an array
              // With a negative size
            int[] array = new int[size];
        } catch (NegativeArraySizeException e) 
        {
            // Handle the NegativeArraySizeException
            System.out.println("Error: Attempted to create an array with a negative size.");
            // Can add more detailed error handling or logging here if needed
        }
    }
}

Output
Error: Attempted to create an array with a negative size.

Explanation of the Program:

Article Tags :