写点什么

Java 中的异常

作者:javaadu
  • 2022 年 3 月 14 日
  • 本文字数:1445 字

    阅读完需:约 5 分钟

异常基础

Error

Error 是 Throwable 的子类,这代表了 Java 程序运行过程中的一种未知原因的错误,当程序运行遇到 Error 的时候,不应该在代码中捕获。跟运行时异常(RuntimeException)一样,Java 代码中的方法签名中不应该声明任何 Error 的子类。

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.


A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.

Exception

Exception 也是 Throwable 的子类,这种运行时的异常情况,是可以在程序中捕获并进行处理的。异常中的运行时异常(RuntimeException)是 Exception 的子类,又称为非受检异常——如果在某个方法中抛出运行时异常,无需在该方法签名上声明运行时异常。

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.


The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.



异常使用原则

  1. 捕获异常的时候,必须打印日志堆栈,并且抛出异常,不能默默地吞掉异常

  2. 异常属于一种方法调用的返回方式,正常的结果通过返回值返回,所有异常情况都通过受检异常进行返回,并设定自定义的异常码和消息,这是一种统一的方法调用方式。


面试题

问题 1:请对比 Exception 和 Error,运行时异常与一般异常有什么区别?

  1. Exception 和 Error 提现了 Java 平台的设计者对程序错误的两种分类。Error 是指平台级别的错误,如果发生某种 xxxxError,则表示 JVM 虚拟机出现了不可回复的错误,例如 OutOfMemoryError;Exception 则表示程序级的错误,在发现异常的时候,可以通过 catch 异常来让程序继续运行,例如 NullPointException。

  2. Exception 又分为受检异常和非受检异常,受检异常是指如果一个方法中如果抛出某个受检异常,则该异常必须声明在方法签名上;非受检异常则不需要声明在方法上。非受检异常就是运行时异常。


问题 2:NoClassDefFoundError 和 ClassNotFoundException 有啥区别?

  1. NoClassDefFoundError 是 Error 的子类,属于不可捕获的错误;ClassNotFoundException 属于一般异常,可以在方法声明并捕获

  2. NoClassDefFoundError:编译的时候可以编译成功,但是当 JVM 在运行时尝试加载一个类的时候,但是没有找到这个类的定义,这时候会抛出 NoClassDefFoundError;

  3. ClassNotFoundException:当应用程序运行的过程中尝试使用类加载器去加载 Class 文件的时候,如果没有在 classpath 中查找到指定的类,就会抛出 ClassNotFoundException,主要是下面三个方法可能抛出 ClassNotFoundException

  4. Class.forName()

  5. ClassLoader.loadClass

  6. ClassLoader.findSystemClass()

发布于: 刚刚阅读数: 3
用户头像

javaadu

关注

功不唐捐 2017.09.10 加入

蚂蚁金服后端开发者,擅长java、spring、spring boot、jvm、分布式架构、软件设计等领域的技术分享,对于风控业务有一定的了解

评论

发布
暂无评论
Java中的异常_Java_javaadu_InfoQ写作平台