首页 > 编程知识 正文

java三大类,java常见的异常类型有哪些

时间:2023-05-06 17:02:52 阅读:156136 作者:15

首先,java的异常分为Error和Exception。 这两个都是接口Throwable的子类。 Error、Exception和cjdhmgsjx类的关系大致可以在下图中简单说明。

注意事项:

1。 Error仅发生在java虚拟机上,用户无需以编程方式捕获或抛出Error。

2。 Exception有两种类型:典型的Exception和RuntimeException。 这里有一个不协调的地方,就是runtimeexception(unchecked )被exception checked )的父类继承了。

PS: checked和unchecked概念理解:

checked :一般是指程序不能直接控制的外界情况,是编译时需要检查的一种exception,在用户程序中可以用try catch机制处理,也可以通过throws传递给调用方进行处理此类异常主要指除Error及RuntimeException及cjdhmgsjx类外的异常。

unchecked :不需要在编译时处理的异常。 在java体系中,所有的Error以及RuntimeException以及cjdhmgsjx类都是unchecked异常。 再坦率地捕捉图像,不需要用try catch等机制处理的异常被认为是unchecked的异常。

checked和unchecked在throwable的继承关系中如下图所示。

------------

| Throwable |

------------

//

//

------- -----------

| error||

------- -----------

//|"

_ _ _ _ _ _/_ _ _ _ _ _ _ _ _/_ _ _ _ _ _ _ _ _ u

------------------

未被解除检查|

------------------

//| () )

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /

未锁定

举例说明上文注意事项2中提到的违和感。

首先定义基本异常类GenericException,并将其继承到Exception中。

1 package check _ unchecked _ exceptions;

2

3 publicclassgenericexceptionextendsexception {

4

5 /**

6 *

7*

8 privatestaticfinallongserialversionuid=2778045265121433720 l;

9

10公共通用表达式(

11

12 }

13

14公共健康检查(string msg ) {

15super(msg );

16 }

17 }

定义测试类VerifyException。

1 package check _ unchecked _ exceptions;

2

3 public class VerifyException {

4

5公共语音第一次(throwsgenericexception {

6检查扩展(checked exception );

7 }

8

9公共语音代码(string msg ) {

10if (msg==空值) {

11 thrownewnullpointerexception (unchecked exception );

12 }

13 }

14

15公共语音隐藏(throwsgenericexception {

16 first (;

17 }

18

19 publicstaticvoidmain (string [ ] args ) {

20 verifyexceptionve=newverifyexception (

21

22 try {

23 ve.first (;

24 )缓存(genericexceptione ) {

25e .打印任务跟踪(;

26 }

27

28ve.second (空;

29 }

30

31 }

运行后,在eclipse控制台中获取以下信息:

1 check _ unchecked _ exceptions.generic exception : checked exception

2at check _ unchecked _ exceptions.verify exception.first (verify exception.Java :6 ) )。

3at check _ unchecked _ exceptions.verify exception.main (verify exception.Java 336023 ) )。

4 exceptioninthread ' main ' Java.lang.nullpointerexception 3360 unchecked exception

5atc heck _ unchecked _ exceptions.verify exception.second (verify exception.Java 3:11 ) )。

6a tcheck _ unchecked _ exceptions.verify exception.main (verify exception.Java 336029 ) )。

在上面的例子中,如果组合checked和unchecked的概念,则名为Exception的父类是checked型,但是cjdhmgsjx类RuntimeException (子类NullPointerException

本文阐述的checked和unchecked的概念是基础性的,但未必大家都理解。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。