Ø 异常处理除了最为常见的“try…catch”应用格式之外,还存在一种结合“try、catch、finally、throw、throws”一起使用的异常处理格式,而在讲解这一应用之前,首先来看一个简单的开发要求:要求定义一个div()方法,而这个方法有如下的一些要求:
Ø 在进行除法操作之前,输出一行提示信息;
Ø 在除法操作执行完毕后,输出一行提示信息;
Ø 如果中间产生了异常,则应该交给被调用处来进行处理。
Ø 而在所有要求之中,第2点和第3点最为麻烦:
Ø 为了保证计算结束之后可以正常的输出信息,则应该使用finally进行操作;
Ø 为了保证异常可以交被调用处使用,应该在方法声明上加上throws,而程序之中也不应该处理异常。
实现要求
class MyMath {
public static int div(int x, int y) throws Exception { // 出现异常要交给被调用处出
System.out.println("===== 计算开始 =====");// 等价于:资源打开
int result = 0;
try { result = x / y; // 除法计算
} catch (Exception e) { throw e; // 向上抛
} finally {
System.out.println("===== 计算结束 ====="); // 等价于:资源关闭
}
return result;
}
}
public class TestDemo {
public static void main(String args[]) {
try {
System.out.println(MyMath.div(10, 0));// 被调用处处理异常
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序执行结果:
===== 计算开始 =====
===== 计算结束 =====
java.lang.ArithmeticException: / by zero
atcom.yootk.demo.MyMath.div(TestDemo.java:7)
atcom.yootk.demo.TestDemo.main(TestDemo.java:19)
简化处理
class MyMath {
public static int div(int x, int y) throws Exception { // 出现异常要交给被调用处出
System.out.println("===== 计算开始 ====="); // 等价于:资源打开
int result = 0;
try {
result = x / y; // 除法计算
} finally {
System.out.println("===== 计算结束 ====="); // 等价于:资源关闭
}
return result;
}
}
public class TestDemo {
public static void main(String args[]) {
try {
System.out.println(MyMath.div(10, 0));// 被调用处处理异常
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序执行结果:
===== 计算开始 =====
===== 计算结束 =====
java.lang.ArithmeticException: / by zero
atcom.yootk.demo.MyMath.div(TestDemo.java:7)
atcom.yootk.demo.TestDemo.main(TestDemo.java:17)