Java中的Exception
2021/10/25 20:41:14
本文主要是介绍Java中的Exception,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Java中的Exceptions主要分:checked exception 和 unchecked exception。我们会分别介绍这两类异常及其使用方法。
Checked Exceptions
从Exception给出的定义,我们可以看到:checked exceptions继承于java.lang.Exception。
The class
Exception
and any subclasses that are not also subclasses of RuntimeException are checked exceptions.
checked exceptions必须用try catch显式地捕获或者throws声明抛出异常。
常见的Checked Exceptions有IOException,SQLException,ClassNotFoundException。还有些常用的exception是继承于IOException的,比如FileNotFoundException,MalformedURLException等等。
有时候在使用引用的时候,但是如果调用的方法抛出了checked exception,我们会发现在调用的时候报错,unhandled exception.
Unchecked Exceptions
同样地,我们也可以从RuntimeException看到unchecked exceptions的介绍,unchecked Exceptions继承于java.lang.RuntimeException。
RuntimeException
and its subclasses are unchecked exceptions.
unchecked exceptions不必捕获异常或者抛出。
经常使用的unchecked exceptions有IllegalArgumentException,NullPointerException,IndexOutOfBoundsException,
选择Checked Exceptions 还是 Unchecked Exceptions
对于checked excpetions,编译器会显式地提醒,这样我们就不会忘记处理异常。
有时候出现异常,我们会习惯写log,但是对于RuntimeException可以不写在log里面。
这篇关于Java中的Exception的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)