Java中异常的抽象类是Throwable,在此基础上。派生出两大类:Error和Exception。

Error是程序中的严重错误,不应该用try…catch包括。Javadoc的说明例如以下:

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.

常见的Error有:AssertionError、OutOfMemoryError、StackOverflowError。

Exception分两类:Checked Exception和Unchecked Exception。

Unchecked Exception的基类是RuntimeException。全部继承自RuntimeException的Exception都属于Unchecked Exception, 如:NullPointerException、ArrayIndexOutOfBoundsException。

Checked Exception直接继承自Exception,全部不继承RuntimeException的Exception都属于Checked Exception,如:FileNotFoundException。

Checked Exception和Unchecked Exception都能够用try…catch包括。当中,Checked Exception在编译时检查是否有想要的catch处理,因此必要有try…catch包括,或者方法签名处抛出相应的异常。而Unchecked Exception在运行时推断,所以不一定要try…catch包括。并且,Unchecked Exception往往是程序本身存在bug,一般不catch这种错误。

备注1:

在try中运行return语句,依旧会运行finally语句块。除非在try语句中结束JVM进程(system.exit(0))

public class Hello{
public static void main(String[] args){
try{
System.out.println("in try");
return;
}catch(Exception e){ }finally{
System.out.println("finally");
}
System.out.println("end");
}
}
//输出
in try
finally

备注2:

不要在finally语句块调用return。否则的话。在try语句块中抛出的异常无法被调用者捕获,例如以下:

    try {
doSomething();
System.out.println("No Exception Caught!");
} catch (RuntimeException e) {
System.out.println("got it.");
}
} public static void doSomething() {
try {
throw new RuntimeException();
} finally {
return;
}
}
//输出
No Exception Caught!

备注3:

throw与throws的差别:

throw是在语句块。程序猿主动抛出一个异常。

throws是在方法的签名处,说明该方法可能抛出的异常。当有多个异常抛出时,用逗号分隔。

备注4:

从JDK7開始,同一个try相应的多个catch能够写在一起。

最新文章

  1. 蒙特·卡罗算法的Python实现
  2. while练习:输入一个班级的人数,然后依次输入学员成绩,计算班级学员的平均成绩和总成绩。
  3. 最新 Arduino 驱动 12接口/户外 LED显示屏/LED点阵屏/LED单元板
  4. 【Sharing】如何成为一名黑客
  5. 查看Linux发行版的名称和版本号
  6. Mongodb: Sort operation used more than the maximum 33554432 bytes of RAM
  7. LeetCode 696 Count Binary Substrings 解题报告
  8. 【九天教您南方cass 9.1】02 从地形图上绘制纵横断面
  9. 阿里云服务器 ECS Linux操作系统加固
  10. ES基本操作
  11. Codeforces787D(SummerTrainingDay06-D 线段树+最短路)
  12. 10款jQuery文本高亮插件
  13. jquery实现返回页面顶部功能。
  14. [Hanani]高数相关知识记录
  15. 洛谷 P1446 [HNOI2008]Cards 解题报告
  16. 设置DatagridView的列头样式
  17. 第01章-欢迎学习VTK
  18. PAT 1108 Finding Average [难]
  19. Selenium Page Object(PO)设计模式
  20. Centos操作系统配置VIP以及网络

热门文章

  1. swift语言点评十七-Designated Initializers and Convenience Initializers
  2. CTSC2012 熟悉的文章 广义后缀自动机_单调队列
  3. CodeForces-722C Destroying Array 并查集 离线操作
  4. py_One
  5. Python学习————字典的增删改查
  6. centos7.3安装php7.0
  7. HDU4324 Triangle LOVE【拓扑排序】
  8. 上传canvas图片到服务器
  9. Gojs学习史(一):基本定义
  10. The IDL compiler