Java NegativeArraySizeException
Example
Create an array with a negative size, and catch the exception:
public class Main {
public static void main(String[] args) {
int size = -3;
try {
int[] myNumbers = new int[size];
} catch (NegativeArraySizeException e) {
System.out.println("The size of an array cannot be negative.");
}
}
}
Definition and Usage
A NegativeArraySizeException happens when you try to create an array with a size below zero.
The size often comes from a calculation or from user input. Check that it is 0 or more before you create the array.
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions