JAVA-BASE-EASY-ERROR-PRONE

JAVA 历年错题记录

  1. 数组越界异常

  2. 空指针异常

  3. 类CastException

    1
    2
    Object obj = new String("10");
    Integer i = (Integer) obj; // 强制类型转换异常
  4. 数组下标越界

  5. 数组类型转换异常

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    int[] arr = {1, 2, 3};
    String[] strArr = (String[]) arr;
    # 数组类型转换异常

    Object[] objArray = new Integer[10];

    objArray[0] = new Integer(123);

    objArray[1] = "hello";
    # // 这会抛出ArrayStoreException,因为String不是Integer的子类,无法存储到Integer类型的数组中
  6. 字符串拼接异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
String str1 = "hello";
String str2 = "world";
String str3 = str1 + str2 + null + 123;
System.out.println(str3);


String str4 = (null + 123) + "hello" + "world";
System.out.println(str4);
# 编译器报错 : java: bad operand types for binary operator '+'
# first type: <nulltype>
# second type: int


String str5 = "hello";
String str6 = null;
String str7 = str5.concat(str6);
System.out.println(str7);
# throw new NullPointerException(); 这里的concat 方法进行了对象拼接。
  1. 字符串索引越界异常

  2. 集合空指针异常

  3. 集合元素不存在异常

  4. 集合元素重复异常

  5. 集合元素类型不一致异常

  6. 集合大小不一致异常

  7. 集合元素排序异常

  8. 日期格式化异常

  9. 反射异常

  10. IO异常

  11. 数据库异常

  12. 事务异常
    与数据库操作相关

    • SQLException
      1
      2
      3
      4
      5
      6
      7
      8
      9
      try {
      connection.setAutoCommit(false);
      // 执行一些SQL操作
      connection.commit();
      } catch (SQLException e) {
      // 处理事务提交失败的情况
      connection.rollback();
      e.printStackTrace();
      }
    • TransactionException
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      try {
      transactionTemplate.execute(new TransactionCallbackWithoutResult() {
      @Override
      protected void doInTransactionWithoutResult(TransactionStatus status) {
      // 执行一些数据库操作
      }
      });
      } catch (TransactionSystemException e) {
      // 处理事务系统错误
      e.printStackTrace();
      }
  13. 线程异常

  14. 网络异常

  15. 序列化异常

  16. 其他异常


JAVA-BASE-EASY-ERROR-PRONE
http://example.com/2025/03/10/develop/Java-basics-error-prone/
作者
YI MING HUANG
发布于
2025年3月10日
许可协议