众所周知,try语句报错,会执行catch语句,然后执行finally,以下这几种情况,看看会如何输出。
1、try语句中包含return,finally包含输出语句
- public static void main(String[] args) {
- // write your code here
- System.out.println(get());
- }
-
- public static String get(){
- try {
- return "111";
- } catch (Exception e) {
- throw new NullPointerException();
- } finally {
- System.out.println(123);
- }
- }
结果:finally正常输出

2、try语句报错,catch语句抛出错误,finally包含输出语句
- public static void main(String[] args) {
- // write your code here
- System.out.println(get());
- }
-
- public static String get(){
- try {
- throw new NullPointerException();
- } catch (Exception e) {
- throw new NullPointerException();
- } finally {
- System.out.println(123);
- }
- }
结果:finally执行成功,再抛出catch中的错误

3、try语句报错,catch包含return,finally包含输出语句
- public static void main(String[] args) {
- // write your code here
- System.out.println(get());
- }
-
- public static String get(){
- try {
- throw new NullPointerException();
- } catch (Exception e) {
- System.out.println(111);
- return "456";
- } finally {
- System.out.println(123);
- }
- }
结果:catch中的语句输出成功,finally中的语句输出成功

4、try和finally中的语句都包含输出
- public static void main(String[] args) {
- // write your code here
- System.out.println(get());
- }
-
- public static String get(){
- try {
- return "123";
- } catch (Exception e) {
- System.out.println(111);
- return "456";
- } finally {
- return "789";
- }
- }
结果:finally成功return

5、try报错,catch和finally包含return语句
- public static void main(String[] args) {
- // write your code here
- System.out.println(get());
- }
-
- public static String get(){
- try {
- throw new NullPointerException();
- } catch (Exception e) {
- System.out.println(111);
- return "456";
- } finally {
- return "789";
- }
- }
结果:finally成功return

6、try包含return,finally抛出错误
- public static void main(String[] args) {
- // write your code here
- System.out.println(get());
- }
-
- public static String get(){
- try {
- return "789";
-
- } catch (Exception e) {
- System.out.println(111);
- return "456";
- } finally {
- throw new NullPointerException();
- }
- }
结果:直接报错

7、try包含报错,catch包含return,finally抛出错误
- public static void main(String[] args) {
- // write your code here
- System.out.println(get());
- }
-
- public static String get(){
- try {
- throw new RuntimeException();
- } catch (Exception e) {
- return "456";
- } finally {
- throw new NullPointerException();
- }
- }
结果:直接报错

通过上面的例子,我们可以得到以下结论: