public void test () {
//1
throw new RuntimeException();
//2
}
基本知识
如果有错误,不进行try-catch则会编译报错。
public void test () {
try {
// 1
throw new NullPointerException();
//2
} catch (RuntimeException r) {
//3
} catch (Exception e) {
//4
} finally {
//5
}
//6
}
基本知识
try-catch中,可以有多个catch,但是catch的错误的类型,从上到下应该是越靠近try的catch的错误类型要越精确,范围越小,不然会编译报错,而且错误只会被, 举个例子:虽然RuntimeException也是Exception,如果你throw出来的是NullPointerException,NullPointerException虽然是Exception,也是RuntimeException,但是如上图代码所示,会优先匹配最靠近这个Exception 的catch,且只会被一个catch匹配,,所以会执行3号区域代码,然后执行5号区域代码,最后执行6号区域代码。
public void test () {
try {
// 1
throw new NullPointerException();
//2
} catch (RuntimeException r) {
//3
} catch (Exception e) {
//4
} finally {
//5
}
//6
}
执行顺序如下:
- 执行1号区域代码
- 由于throw了RuntimeException 则会直接执行对应的3号区域的代码
- 执行5号区域的代码
- 执行6好区域的代码
public int testFinally () {
int a = 0 ;
try {
1
throwException();
2 return a;
} catch (RuntimeException r) {
3 System.out.println("RuntimeException");
4 return a;
} catch (Exception e) {
5 System.out.println("Exception");
} finally {
6 System.out.println("finally");
7 a=1;
}
return 0;
}
public void throwException () {
throw new RuntimeException();
}
执行顺序如下:
- 1号区域代码
- 3号区域代码
- 4号区域代码,但是此时不会直接返回,而是将a的值复制保存一份
- 6号区域代码
- 7号区域代码,但是此时已经不会影响a在第3步的值
- 4号区域代码,return 结束函数 此时a=0
public int testFinally () {
int a = 0 ;
try {
1
throwException();
2 return a;
} catch (RuntimeException r) {
3 System.out.println("RuntimeException");
4 return a;
} catch (Exception e) {
5 System.out.println("Exception");
} finally {
6 System.out.println("finally");
7 a=1;
8 return a;
}
9 System.out.println("Exception");
10 return a;
}
public void throwException () {
throw new RuntimeException();
}
执行顺序如下:
- 1号区域代码
- 3号区域代码
- 4号区域代码,但是此时不会直接返回,而是将a的值复制保存一份
- 6号区域代码
- 7号区域代码,但是此时已经不会影响在第3步的要返回的值
- 8号区域代码,此时a=1 此时 return a=1,结束函数
9,10不会执行。
这就是为什么一般finally不写return。