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要写在最后。