java学习之异常

throw:
抛出一个异常对象两种处理:
1.使用try-catch捕获处理异常
2.将异常抛出并且在方法中声明
throws:将异常抛给调用的方法
区别:
位置不同
throw
产生于方法体内
throws在方法声明处
作用不同:
throw 产生并抛出异常,原则是谁调用谁处理
throws:
声明当前方法有异常产生,调用者在调用当前方法的时候,需要进行异常处理
数量不同:
throw 只能产生一个异常对象

throws 可以声明多个异常类用","隔开


public void divide(int num1,int num2){
		int re;
		re = num1/num2;
		System.out.println(re);
	}
	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);
		
		int num1 = in.nextInt();
		int num2 = in.nextInt();
		new test().divide(num1, num2);

如果不做处理的结果会有:



那么我们就使用try-catch

	
		Scanner in = new Scanner(System.in);
		try{
		int num1 = in.nextInt();
		int num2 = in.nextInt();
		new test().divide(num1, num2);
		
		}catch(ArithmeticException e){
			System.out.println("0不能做除数");
		}catch (InputMismatchException e) {
			System.out.println("输入格式不正确");
		}finally {
			System.out.println("--------------finally-------------");
		}
		





最后我们看看thows和throw

	public static void main (String[] args)throws Exception {
		
		Scanner in = new Scanner(System.in);
		try{
		int num1 = in.nextInt();
		int num2 = in.nextInt();
		new test().divide(num1, num2);
		throw new Exception("不能被0除");
}
		


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值