(四)异常的捕捉和处理
6.1处理异常
public class TestDemo9 {
//处理异常
public static void main(String args[]){
System.out.println("开始执行");
try{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
System.out.println("除法计算"+x/y);
//如果产生了异常 这下面这条语句不执行
System.out.println("这里不执行了");
}catch (ArrayIndexOutOfBoundsException e){
//处理数组溢出异常
e.printStackTrace();
}catch(NumberFormatException e){
e.printStackTrace();
}catch (ArithmeticException e){
e.printStackTrace();
}
finally{
System.out.println("我一直会执行");
}
System.out.println("j计算结束");
}
}
这里需要注意几个地方:
1、catch内部采用printStackTrace来输出异常信息
2、try内的语句,在异常出现之后的语句都不执行
3、finally中的语句一直会执行
4、关于最后一个语句,如果异常全部处理了,那么它会执行,如果有异常未被处理,那他就不执行。
4.2异常处理流程
这里要注意的几点:
1、处理多个异常时,捕获范围小的异常要放在捕获范围大的异常前处理
catch(NumberFormatException e){
}
catch(Exeption e){
}
上述代码表示捕获所有异常,如果你捕获一个数组越界异常,需要写到这个前面
4.3throws关键字
throws关键字主要在方法定义上使用,表示此方法不进行异常的处理,而是交给被调用处处理
class MyMath{
public static int div(int x,int y) throws Exception{
return x/y;
}
}
public static void main(String args[]){
try{
System.out.print(MyMath.div(10,2);
}catch(Exception e){
e.printStackTrace();
}
}
上述代码表示此方法不处理异常。
div方法抛出异常,必须在使用时明确进行异常处理。
4.4throw关键字
这个关键字表示的是用户自己手工抛出一个实例化对象(手工调用异常类的构造方法)
与throws的区别在于:
1、throw指的是在方法中人为抛出一个异常类对象
2、throws在方法的声明上使用,表示此方法在调用时必须处理异常。
4.5异常处理的标准格式
finally中语句不会执行的另一种情况。
public class TestDemo10 {
public static int div(int x,int y)throws Exception{
System.out.println("开始");
int result=0;
result=x/y;
try{
//如果try里面不写执行语句 就不会进入try语句中 finally中语句就不会执行
}catch (Exception e){
throw e;
}
finally {
System.out.println("结束");
}
return result;
}
public static void main(String args[]){
try{
System.out.println(div(10,0));
}catch (Exception e){
e.printStackTrace();
}
}
}
标准形式
public class TestDemo10 {
public static int div(int x,int y)throws Exception{
System.out.println("开始");
int result=0;
try{
result=x/y;
//如果try里面不写执行语句 就不会进入try语句中 finally中语句就不会执行
}catch (Exception e){
throw e;
}
finally {
System.out.println("结束");
}
return result;
}
public static void main(String args[]){
try{
System.out.println(div(10,0));
}catch (Exception e){
e.printStackTrace();
}
}
}
4.6RuntimeException
RuntimeException是Exception的子类,Exception定义了必须处理的异常,而RuntimeException定义的异常可以选择性进行处理。
常见的RuntimeException的异常包括:NumberFormatException ClassCastException