java try catch throw 区别_Java: 关于try-catch-finally中catch语句块里return和throw的差别问题...

330291ff1c8b43510879c977de0f333f.png

557daf646c418b5179ce3f3a92240dd7.png

这两张图可以清楚的看出来这两者之间的区别了,第一个例子中,在areturn这个指令之前,已经计算出了最后的返回值,setName是在areturn这个指令之后调用;第二个例子,就是正常执行,addSuppressed是在return之前调用。建议题主从jvm指令这个角度分析一下。

贴出我的代码:

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import org.junit.Test;

public class TestExample {

public static class Student {

private String name;

private int age;

public Student(String name, int age) {

this.name = name;

this.age = age;

}

@Override

public String toString() {

// TODO Auto-generated method stub

return "Name is " + name + " age is " + age;

}

public void setName(String string) {

this.name = string;

}

}

public String get() {

Student s = new Student("lily", 3); // name, age

try {

int i = 3;

int j = i / 0;

return s.toString();

} catch (Exception e) {

Student t = s;

return t.toString(); // 语句1

} finally {

s.setName("baga");

System.out.println(s.toString()); // 语句2

}

}

@Test

public void test1() {

try {

File file = new File("");

FileInputStream fis = new FileInputStream(file);

Throwable t = null;

try {

fis.read();

} catch (Throwable t1) {

t = t1;

throw t1;

} finally {

if (fis != null) {

if (t != null) {

try {

fis.close();

} catch (Throwable t2) {

t.addSuppressed(t2);

}

} else {

fis.close();

}

}

}

} catch (IOException e3) {

}

}

@Test

public void test() {

String result = get();

System.out.print(result);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值