学习目标:初步了解异常的用法
- 初步接触java中的异常机制
学习内容:
- 异常体系结构
- 异常处理机制
- 经验总结
学习时间:
20分钟
学习产出:
1.异常体系结构
基类java.lang.Throwable --> 子类Error和Exception
2.异常处理机制
- 在方法中使用try...catch语句捕获并处理异常,catch语句可以有若干个,用以匹配多个异常
catch中出现的异常书写顺序:子类 -> 父类,即从小到大
原因:先被catch捕获到的异常执行后,将不执行该catch语句之后的catch
以下程序输出为:
出现错误...
程序结束
public class ExceptionDemo {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
new ExceptionDemo().A();
}catch (Error e){
System.out.println("出现错误...");
}catch (Exception e){
System.out.println("出现异常...");
}catch (Throwable t){
System.out.println("出现throw...");
}finally {
System.out.println("程序结束");
}
}
public void A() {
B();
}
public void B() {
A();
}
}
- 在方法声明处使用throw和throws主动抛出异常,由上层进行处理
throw案例:
public class ExceptionDemo {
public static void main(String[] args) {
int a = 1;
int b = 0;
new ExceptionDemo().divide(a, b);
}
public void divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException(); // 主动抛出异常,一般在方法中使用
}
}
}
throws案例:
public class ExceptionDemo {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
new ExceptionDemo().divide(a, b);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
// 如果该方法中处理不了该异常,则使用throws向上级调用者抛出该异常
public void divide(int a, int b) throws ArithmeticException{
if (b == 0) {
throw new ArithmeticException(); // 主动抛出异常
}
}
}
3.经验总结
- 处理运行时异常,采用try-catch处理
- 在多重catch之后添加一个catch(Exception)来捕获可能遗漏的异常
- 尽量添加finally语句块去释放占用的资源