### 1. 空指针异常(NullPointerException)

错误原因:调用空对象的属性或方法。

```java

String str = null;

System.out.println(str.length()); // 抛出异常

```

解决方法:

- 添加非空判断

```java

if (str != null) {

System.out.println(str.length());

}

```

- 使用Optional类(Java 8+)

```java

Optional.ofNullable(str).ifPresent(s -> System.out.println(s.length()));

```

### 2. 数组越界异常(ArrayIndexOutOfBoundsException)

错误原因:访问不存在的数组索引。

```java

int[] arr = {1,2,3};

System.out.println(arr[5]); // 索引超出范围

```

解决方法:

- 检查索引范围

```java

int index = 5;

if (index >= 0 && index < arr.length) {

System.out.println(arr[index]);

}

```

### 3. 类型转换异常(ClassCastException)

错误原因:不安全的强制类型转换。

```java

Object obj = hello;

Integer num = (Integer) obj; // 转换失败

```

解决方法:

- 使用instanceof检查类型

```java

if (obj instanceof Integer) {

Integer num = (Integer) obj;

}

```

### 4. 数字格式化异常(NumberFormatException)

错误原因:将非数字字符串转换为数值类型。

```java

String str = abc;

int num = Integer.parseInt(str); // 转换失败

```

解决方法:

- 使用正则表达式验证

```java

if (str.matches(-?\d+)) {

int num = Integer.parseInt(str);

}

```

### 5. 并发修改异常(ConcurrentModificationException)

错误原因:在遍历集合时修改集合内容。

```java

List list = new ArrayList<>();

list.add(a);

for (String s : list) {

list.remove(s); // 遍历时删除元素

}

```

解决方法:

- 使用迭代器的remove方法

```java

Iterator it = list.iterator();

while (it.hasNext()) {

it.next();

it.remove();

}

```

### 6. 字符串索引越界异常(StringIndexOutOfBoundsException)

错误原因:访问字符串不存在的字符位置。

```java

String str = hi;

char ch = str.charAt(5); // 索引超出范围

```

解决方法:

- 检查字符串长度

```java

int index = 5;

if (index >= 0 && index < str.length()) {

char ch = str.charAt(index);

}

```

### 7. 算术异常(ArithmeticException)

错误原因:数学运算错误,如除零。

```java

int a = 5 / 0; // 除零错误

```

解决方法:

- 添加除数检查

```java

int divisor = 0;

if (divisor != 0) {

int result = 5 / divisor;

}

```

### 8. 数字溢出错误(数值范围越界)

错误原因:超出数据类型的数值范围。

```java

int max = Integer.MAX_VALUE;

int overflow = max + 1; // 结果错误

```

解决方法:

- 使用更大范围的数据类型

```java

long result = (long)Integer.MAX_VALUE + 1;

```

- 使用Math.addExact(Java 8+)

```java

try {

int result = Math.addExact(Integer.MAX_VALUE, 1);

} catch (ArithmeticException e) {

// 处理溢出

}

```

### 9. 日期解析异常(DateTimeParseException)

错误原因:日期字符串格式不匹配。

```java

String dateStr = 2023/13/45;

LocalDate date = LocalDate.parse(dateStr); // 格式错误

```

解决方法:

- 指定日期格式器

```java

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(yyyy/MM/dd);

try {

LocalDate date = LocalDate.parse(dateStr, formatter);

} catch (DateTimeParseException e) {

// 处理解析失败

}

```

### 10. 集合操作异常(UnsupportedOperationException)

错误原因:对不可变集合执行修改操作。

```java

List list = Arrays.asList(a, b);

list.add(c); // 不支持的操作

```

解决方法:

- 创建可修改的集合副本

```java

List mutableList = new ArrayList<>(Arrays.asList(a, b));

mutableList.add(c);

```

### 预防建议

1. 始终进行参数验证

2. 使用IDE的静态代码分析工具

3. 编写单元测试覆盖边界情况

4. 阅读API文档了解方法的使用限制

5. 使用try-catch处理可能的异常情况

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐