try-catch以及try-catch-finally

try-catch以及try-catch-finally

语法:

try{
	//一些会抛出异常的方法
}catch(Exception e){
	//处理该异常的代码块
}finally{
	//最终将要执行的一些代码
}

解释:

(1)如果try抛出异常,程序会终止执行,程序的控制权会转移交给catch块中的异常处理程序

(2)try语句块不可以独立存在,必须与catch或finally块共存

(3)用try-catch语句块处理完异常还需进行一些善后工作,比如关闭连接或关闭打开的一些文件,则用finally语句块进行善后工作


例如:

import java.util.InputMismatchException;
import java.util.Scanner;
public class Exception{
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		try{
			int m=in.nextInt();
			int n=in.nextInt();
			System.out.println("Sum is "+(m+n));
		}
		catch(InputMismatchException e){
			System.out.println("Incorrect input and re-enter two integers");
		}
	}
}

运行结果:

i 8
Incorrect input and re-enter two integers


try抛出多种类型的异常:

例如:

public class ExceptionTest{
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		try{
			System.out.println("请输入第一个数:");
			int m=in.nextInt();
			System.out.println("请输入第二个数:");
			int n=in.nextInt();
			System.out.println(m+"/"+n+"="+m/n);
		}
		catch(InputMismatchException e){
			System.out.println("输入类型不正确,请输入整数");
		}
		catch(ArithmeticException e){
			System.out.println("除数不能为0");
		}
		catch(Exception e){
			//Exception是InputMismatchException和ArithmeticException两个类的父类
		}
		finally{
			//最终要执行的一些代码
		}
	}
}

运行结果(三组数据):

请输入第一个数:
3
请输入第二个数:
0
除数不能为0


请输入第一个数:
f
输入类型不正确,请输入整数


请输入第一个数:
4
请输入第二个数:
2
4/2=2

注意:编写多重catch块时要先子类后父类,如上面的代码,Exception要写在最后。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值