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

错误场景:调用`null`对象的方法或访问属性。

```java

String str = null;

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

```

解决方案:

- 使用前检查对象是否为`null`:

```java

if (str != null) {

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

}

```

- 使用`Optional`类避免空指针:

```java

Optional optionalStr = Optional.ofNullable(str);

System.out.println(optionalStr.orElse().length());

```

---

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

错误场景:强制类型转换时类型不匹配。

```java

Object obj = Hello;

Integer num = (Integer) obj; // 抛出ClassCastException

```

解决方案:

- 使用`instanceof`进行类型检查:

```java

if (obj instanceof Integer) {

Integer num = (Integer) obj;

}

```

---

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

错误场景:访问数组时索引超出范围。

```java

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

System.out.println(arr[5]); // 抛出ArrayIndexOutOfBoundsException

```

解决方案:

- 检查索引是否在有效范围内:

```java

int index = 5;

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

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

}

```

---

### 4. StringIndexOutOfBoundsException(字符串越界异常)

错误场景:访问字符串时索引超出范围。

```java

String str = Hi;

char ch = str.charAt(5); // 抛出StringIndexOutOfBoundsException

```

解决方案:

- 检查索引是否在字符串长度范围内:

```java

int index = 5;

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

char ch = str.charAt(index);

}

```

---

### 5. NumberFormatException(数字格式异常)

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

```java

String str = abc;

int num = Integer.parseInt(str); // 抛出NumberFormatException

```

解决方案:

- 使用正则表达式或异常捕获:

```java

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

int num = Integer.parseInt(str);

}

```

```java

try {

int num = Integer.parseInt(str);

} catch (NumberFormatException e) {

System.out.println(无效的数字格式);

}

```

---

### 6. IllegalArgumentException(非法参数异常)

错误场景:传入不合法参数。

```java

public void setAge(int age) {

if (age < 0 || age > 150) {

throw new IllegalArgumentException(年龄无效);

}

}

```

解决方案:

- 在方法中验证参数:

```java

public void setAge(int age) {

if (age < 0 || age > 150) {

throw new IllegalArgumentException(年龄必须在0到150之间);

}

this.age = age;

}

```

---

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

错误场景:在遍历集合时修改集合内容。

```java

List list = new ArrayList<>();

list.add(A);

for (String s : list) {

list.remove(s); // 抛出ConcurrentModificationException

}

```

解决方案:

- 使用迭代器的`remove`方法:

```java

Iterator iterator = list.iterator();

while (iterator.hasNext()) {

String s = iterator.next();

iterator.remove();

}

```

---

### 8. StackOverflowError(栈溢出错误)

错误场景:递归调用无终止条件。

```java

public void recursiveMethod() {

recursiveMethod(); // 无限递归,抛出StackOverflowError

}

```

解决方案:

- 添加递归终止条件:

```java

public void recursiveMethod(int n) {

if (n <= 0) return;

recursiveMethod(n - 1);

}

```

---

### 9. NoClassDefFoundError(类定义未找到错误)

错误场景:运行时缺少依赖的类文件。

```java

// 编译通过,但运行时缺少依赖类

```

解决方案:

- 检查类路径是否包含所有依赖的JAR文件或类文件。

---

### 10. ClassNotFoundException(类未找到异常)

错误场景:动态加载类时找不到类定义。

```java

Class.forName(com.example.NonExistentClass); // 抛出ClassNotFoundException

```

解决方案:

- 确保类名正确且类路径包含该类:

```java

try {

Class clazz = Class.forName(com.example.ExistingClass);

} catch (ClassNotFoundException e) {

System.out.println(类未找到,请检查类名和类路径);

}

```

---

### 总结

以上是Java开发中常见的数据类型相关错误及解决方案。通过提前检查、异常捕获和代码规范,可以有效避免这些问题,提升代码健壮性。

Logo

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

更多推荐