java异常处理总结

1、java异常处理中,一个域内抛出异常(11行抛出异常,12、13行代码不再执行),并用catch捕获并处理后,域之后的代码是继续执行的(19,20行),如果域的catch后面包含finally语句,是执行完finally里面的代码(17行)后,再继续执行后续代码(19、20行)。

1 public class ExceptionTest {
2
3
4 class MyException extends Exception{
5
6 }
7
8 String sf1() {
9 int i = 0;
10 try{
11 if(i==0)throw new MyException();
12 System.out.println("IN");
13 return null;
14 }catch(MyException e){
15 System.out.println("CATCH");
16 }finally{
17 System.out.println("FINALLY");
18 }
19 System.out.println("OUT");
20 return null;
21
22 }
23 /**
24 * @param args
25 */
26 public static void main(String[] args){
27 // TODO Auto-generated method stub
28 new ExceptionTest().sf1();
29 }
30
31 }
//console output
CATCH
FINALLY
OUT

2、即便函数已经通过return 返回,如果返回语句外围有catch、finally语句包围,finally语句内容还是可以被执行的(18行)。

1 public class ExceptionTest {
2
3
4 class MyException extends Exception{
5
6 }
7
8 String sf1() {
9 int i = 0;
10 try{
11 if(i!=0)
12 throw new MyException();
13 System.out.println("IN");
14 return null;
15 }catch(MyException e){
16 System.out.println("CATCH");
17 }finally{
18 System.out.println("FINALLY");
19 }
20 System.out.println("OUT");
21 return null;
22
23 }
24 /**
25 * @param args
26 */
27 public static void main(String[] args){
28 // TODO Auto-generated method stub
29 new ExceptionTest().sf1();
30 }
31
32 }
//console output
IN
FINALLY


3、 如果一个函数声明了异常,函数体内通过throw抛出了此异常且外围没有用try、catch去捕获的话,则函数到此执行结束,不过如果外围有try、 finally语句,final里面的语句还是要执行的(第14行)。不过整个域后面的代码是不会在执行了(第16行)。

1 public class ExceptionTest {
2
3
4 class MyException extends Exception{
5
6 }
7
8 String sf1() throws MyException {
9 int i = 0;
10 try{
11 if(i==0)throw new MyException();
12 System.out.println("IN");
13 }finally{
14 System.out.println("FINALLY");
15 }
16 System.out.println("OUT");
17 return null;
18
19 }
20 /**
21 * @param args
22 */
23 public static void main(String[] args) throws MyException {
24 // TODO Auto-generated method stub
25 new ExceptionTest().sf1();
26 }
27
28 }
//console output

FINALLY
Exception in thread "main" ExceptionTest$MyException
    at ExceptionTest.sf1(ExceptionTest.java:11)
    at ExceptionTest.main(ExceptionTest.java:25)


4、其他:

  1)函数可以声明了异常,但不抛出。

  2)函数内部捕获了异常,并在catch和finally里面没有抛出新异常的情况下,是不用函数声明的。只有函数内存在没有被捕获的异常时,才需要函数声明异常。

  3)子类在重构父类包含异常声明的函数时,不能添加新的异常声明(指不是父类方法中声明的异常的扩展异常),但可以减少。

posted @ 2011-04-21 12:43  奋奋  阅读(463)  评论(0编辑  收藏  举报