# java.lang.NegativeArraySizeException

- **ID:** `java/negative-array-size`
- **领域:** java
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 87%

## 根因

当使用负数大小创建数组时抛出，通常是由于整数溢出或数组大小计算错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Java 8 | active | — | — |
| Java 11 | active | — | — |
| Java 17 | active | — | — |
| Java 21 | active | — | — |

## 解决方案

1. ```
   Validate the array size before creation: `if (size < 0) throw new IllegalArgumentException("Size must be non-negative: " + size);`.
   ```
2. ```
   Use long arithmetic for size calculation to prevent integer overflow: `long safeSize = (long) a * b; if (safeSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Size too large");`.
   ```
3. ```
   Add a guard clause: `int size = computeSize(); if (size < 0) { size = 0; }` to handle edge cases gracefully.
   ```

## 无效尝试

- **** — The root cause (negative size) is not fixed; retrying will throw the same exception. (95% 失败率)
- **** — This masks the underlying bug and may lead to incorrect program behavior or data loss. (70% 失败率)
- **** — If the size is Integer.MIN_VALUE, Math.abs() returns a negative value due to overflow, still causing the exception. (80% 失败率)
