java异常的捕获及处理 兼论throws与throw
java异常处理可以使用try…catch语句进行处理,也可以使用try…catch…fianlly进行处理。在try语句中捕获异常,在catch语句中处理异常,finally做为异常的统一出口,不管是否发生了异常都要执行此段代码。
throws用在方法申明处,表示本方法不处理异常,有异常向上抛,交给被调用处处理;throw在方法中由用户手工抛出一个异常的实例化对象。
下面比较两段代码和执行结果可以看出异常处理的过程和throws及throw的用法。
第一段代码:
package cn.mldn.demo;
class MyMath{
public int div(int x, int y) throws Exception{
System.out.println("-------计算开始----------");
int result = 0;
try { //捕捉异常
result = x/y;
} catch (Exception e) { //处理异常
e.printStackTrace();
System.out.println("--------处理异常1----------");
// throw e; //手工抛出异常
}finally{
System.out.println("--------计算结束----------");
}
return result;
}
}
public class TestDemo{
public static void main(String args[]){
try {
System.out.println("运算结果:" + new MyMath().div(10, 0));
} catch (Exception e) {
e.printStackTrace();
System.out.println("--------处理异常2----------");
}
}
}
代码执行结果如下:
可以看到,在public int div(int x, int y) throws Exception方法中由try…catch…finally处理了异常后尽管方法有throws Exception也不会抛出异常给main。
第二段代码:
package cn.mldn.demo;
class MyMath{
public int div(int x, int y) throws Exception{
System.out.println("-------计算开始----------");
int result = 0;
try { //捕捉异常
result = x/y;
} catch (Exception e) { //处理异常
e.printStackTrace();
System.out.println("--------处理异常1----------");
throw e; //手工抛出异常
}finally{
System.out.println("--------计算结束----------");
}
return result;
}
}
public class TestDemo{
public static void main(String args[]){
try {
System.out.println("运算结果:" + new MyMath().div(10, 0));
} catch (Exception e) {
e.printStackTrace();
System.out.println("--------处理异常2----------");
}
}
}
代码执行结果如下:
可以看到,在public int div(int x, int y) throws Exception方法中由try…catch…finally处理了异常时,由于
throw e; //手工抛出异常
手工抛出了异常,由throws继续向上抛出该异常,交给被调用处main处理,所以main中捕获到了该异常,执行了
catch (Exception e) {
e.printStackTrace();
System.out.println("--------处理异常2----------");
}
这段代码。