范例:实现合理的异常处理
class MyMath {
public static int div(int x, int y) throws Exception {// 异常抛出
int temp = 0;
System.out.println("*** 【START】除法计算开始 ***");/ 开始提示信息
try {
temp = x / y; // 除法计算
} catch (Exception e) {
throw e; // 抛出捕获到的异常对象
} finally {
System.out.println("*** 【END】除法计算结束 ***");// 结束提示信息
}
return temp;// 返回计算结果
}
}
public class JavaDemo {
public static void main(String args[]) {
try {
System.out.println(MyMath.div(10, 0));// 调用计算方法
} catch (Exception e) {
e.printStackTrace();
}
}}
范例:使用简化异常模型
class MyMath {
public static int div(int x, int y) throws Exception { // 异常抛出
int temp = 0;
System.out.println("*** 【START】除法计算开始 ***");// 开始提示信息
try {
temp = x / y; // 除法计算
} finally {
System.out.println("*** 【END】除法计算结束 ***");// 结束提示信息
}
return temp; // 返回计算结果
}
}