异常

目录

一、异常体系

二、Throwable

三、Error

四、Exception


Java中,异常表示程序运行过程中发生的某种已知或者未知的不正确的行为。这种行为,会影响甚至终止程序的正确运行。在实际编程中,我们会遇到各种类型的异常,接下来由分四部分对异常进行简要的介绍。

一、异常体系

  

在Java中,Throwable是所有异常的父类。根据UML图,我们可知,异常分为Error和Exception两大类。

二、Throwable

在JDK中,对Throwable的描述如下:

The {@code Throwable} class is the superclass of all errors and
 * exceptions in the Java language. Only objects that are instances of this
 * class (or one of its subclasses) are thrown by the Java Virtual Machine or
 * can be thrown by the Java {@code throw} statement. Similarly, only
 * this class or one of its subclasses can be the argument type in a
 * {@code catch} clause.

1)Throwable是Java中所有错误与异常的父类;

2)只有Throwable或者其子类才能被JVM或者通过throw语句抛出;

3)同理,catch声明语句中的参数也必须是Throwable或者其子类

三、Error

在JDK中,对Error的描述如下:

 * An {@code Error} is a subclass of {@code Throwable}
 * that indicates serious problems that a reasonable application
 * should not try to catch. Most such errors are abnormal conditions.

1)Error是Throwable的子类;

2)应用程序不应该试图捕获Error;

3)大多数Error是非正常条件

Error是Throwable的子类,根据Throwable的描述,它是可以通过throw语句抛出或者在catch语句中声明的,虽然没什么用,在实际项目中,很少遇到这种用法。

四、Exception

JDK对Exception的描述:

/**
 * The class {@code Exception} and its subclasses are a form of
 * {@code Throwable} that indicates conditions that a reasonable
 * application might want to catch.
 *
 * <p>The class {@code Exception} and any subclasses that are not also
 * subclasses of {@link RuntimeException} are <em>checked
 * exceptions</em>.  Checked exceptions need to be declared in a
 * method or constructor's {@code throws} clause if they can be thrown
 * by the execution of the method or constructor and propagate outside
 * the method or constructor boundary.

1)Exception及其子类是一种应用程序应该捕获Throwable类型;

2)非RuntimeException是受检查异常;

3)受检查异常需要在方法或者构造方方法的throws语句中声明

异常分为受检查异常和不受检查异常。受检查异常又称为编译时异常(CompileTimeException),不受检查异常又称运行时异常(RumtimeException)。根据3)描述,编译时异常通常表示某种外部条件不满足,而导致程序运行发生错误,需要在方法声明中通过throws语句抛出或者在catch块中捕获处理。而运行时异常则表示的是编码过程中的某种未考虑的条件,Java程序运行中能够自动检测。

常见的受检查异常:FileNotFoundException,IOException,SocketException.

常见的不受检查异常:ArrayIndexOutOfBoundException,NullPointerException,IllegalStateException.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值