JavaSE(三)异常处理

1:把不同类型的异常情况描述成不同类(称之为异常类).
2:分离异常流程代码和正确流程代码.
3:灵活处理异常,如果当前方法处理不了,应该交给调用者来处理.
1.try catch
用于捕获异常


public class MultiCatchDemo {
	public static void main(String[] args) {
		String num1 = "50";
		String num2 = "0b";
		try {
			int ret1 = Integer.parseInt(num1); // String类型转换为int类型
			int ret2 = Integer.parseInt(num2);// String类型转换为int类型
			System.out.println("===============");
			int ret = ret1 / ret2;
			System.out.println("结果为" + ret);

		} catch (ArithmeticException e) {  //处理算数异常
			System.out.println("异常类型1");
			e.printStackTrace();
		} catch (NumberFormatException e) {//处理数字格式化异常
			System.out.println("异常类型2");
			e.printStackTrace();
		}catch (Exception e) { //都不满足上述异常类型的时候执行这里 ,在所有catch之后
			System.out.println("异常类型3");
			e.printStackTrace();
		}
	}
}

在这里插入图片描述
在这里插入图片描述
注意:
1:一个catch语句,只能捕获一种类型的异常,如果需要捕获多种异常,就得使用多个catch语句.
2):代码在一瞬间只能出现一种类型的异常,只需要一个catch捕获,不可能同时出现多个异常.
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
2.finally
inally语句块表示最终都会执行的代码,无论有没有异常.
什么时候的代码必须最终执行:
当我们在try语句块中打开了一些物理资源(磁盘文件/网络连接/数据库连接等),我们都得在使用完之后,最终关闭打开的资源.
finally的两种语法:
1):try…finally: 此时没有catch来捕获异常,因为此时根据应用场景,我们会抛出异常,自己不处理.
2):try…catch…finally:自身需要处理异常,最终还得关闭资源.
在这里插入图片描述
3.throw
抛出异常:
throw: 运用于方法内部,用于给调用者返回一个异常对象,和return一样会结束当前方法.
throws: 运用于方法声明之上,用于表示当前方法不处理异常,而是提醒该方法的调用者来处理异常(抛出异常).
如:private static int divide(int num1, int num2) throws Exception {}
throw:
一般的,当一个方法出现不正常的情况的时候,我们不知道该方法应该返回什么,此时就返回一个错误,在catch语句块中继续向上抛出异常.
return 是返回一个值,throw 是返回一个错误,返回给该方法的调用者.

public class ThrowsDemo {
	public static void main(String[] args) throws Exception {
		divide(10, 0);
}

	//在本方法中不处理某种类型的异常,提醒调用者需要来处理该异常
private static int divide(int num1, int num2) throws Exception {
	System.out.println("begin...");
	if (num2 == 0) {
		throw new Exception("除数不能为0");//此处如果为RuntimeException就不会编译出错
	}
											
	try {
		int ret = num1 / num2;
		System.out.println("结果 =" + ret);
		return ret;
	} catch (ArithmeticException e) {
		e.printStackTrace();
	}
	System.out.println("end....");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37282683/article/details/88727294
今日推荐