Java常见的10个异常

1.NullPointerException

空指针异常,当操作一个 null 对象的方法或属性时会抛出这个异常。是一个很头疼的异常,因为它是运行时异常,不需要手动捕获,但运行时碰到这个异常会中断程序。

2.OutOfMemoryError

 内存溢出异常,这不是程序能控制的,当需要分配的对象的内存超出了当前最大的堆内存,需要调整堆内存大小(-Xmx)以及优化程序。

3.IOException

IO,即:Input、Output,我们在读写磁盘文件、网络内容的时候经常会生的一种异常,这种异常是受检查异常,需要进行手工捕获。

比如读写文件是需要抛出异常:

点击查看代码
public int read() throws IOException
public void write(int b) throws IOException

4.FileNotFoundException

找不到文件异常,如果文件不存在就会抛出这种异常。

如定义输入输出文件流,文件不存在会报错:

点击查看代码
public FileInputStream(File file) throws FileNotFoundException
public FileOutputStream(File file) throws FileNotFoundException

FileNotFoundException 其实是 IOException 的子类,同样是受检查异常,需要进行手工捕获。

5.ClassNotFoundException

 类找不到异常,Java开发中经常遇到的一种异常,这是在加载类的时候抛出来的,即在类路径下不能加载指定的类。它是受检查异常,需要进行手工捕获。

点击查看代码
public static <T> Class<T> getExistingClass(ClassLoader classLoader, String className) {
  try {
     return (Class<T>) Class.forName(className, true, classLoader);
  }
  catch (ClassNotFoundException e) {
     return null;
  }
}

6.ClassCastException

类转换异常,将一个不是该类的实例转换成这个类就会抛出这个异常。

如将一个数字强制转换成字符串就会报这个异常:

点击查看代码
Object x = new Integer(0);
System.out.println((String)x);

7.NoSuchMethodException

未找到方法异常,一般发生在反射调用方法的时候:

点击查看代码
public Method getMethod(String name, Class<?>... parameterTypes)
    throws NoSuchMethodException, SecurityException {
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
    Method method = getMethod0(name, parameterTypes, true);
    if (method == null) {
        throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
    }
    return method;
}

8.IndexOutOfBoundsException

索引越界异常,当操作一个字符串或者数组的时候经常遇到的异常。

9.ArithmeticException

算术异常,发生在数字的算术运算时的异常,如一个数字除以 0 就会报这个错。

此异常虽然是运行时异常,可以手工捕获抛出自定义的异常,如:

点击查看代码
public static Timestamp from(Instant instant) {
    try {
        Timestamp stamp = new Timestamp(instant.getEpochSecond() * MILLIS_PER_SECOND);
        stamp.nanos = instant.getNano();
        return stamp;
    } catch (ArithmeticException ex) {
        throw new IllegalArgumentException(ex);
    }
}

10.SQLException

SQL异常,发生在操作数据库时的异常。

如下面的获取数据库连接时:

点击查看代码
public Connection getConnection() throws SQLException {
    if (getUser() == null) {
        return DriverManager.getConnection(url);
    } else {
        return DriverManager.getConnection(url, getUser(), getPassword());
    }
}
posted @   我睡觉时候不困  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示