11.7 exception handling model

Example: to achieve a reasonable exception handling

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();
		}
	}}

Example: the use of simplified exception model

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;	// 返回计算结果
	}
}
Published 162 original articles · won praise 9 · views 3081

Guess you like

Origin blog.csdn.net/ll_j_21/article/details/104734757