在Java中try…catch…finally是我们经常用到的代码,今天我们就来搞清楚其中的返回值和执行顺序的问题
下面给一段代码:
public class Test {
public static void main(String[] args) {
System.out.println(tryReturn());
}
public static int tryReturn() {
try {
int i = 4/1;
System.out.println("没有遇到异常");
return 1;
} catch (Exception e) {
// TODO: handle exception
}finally {
}
return 2;
}
}
上面代码的执行结果是什么呢?是tryReturn()是返回1还是2呢?
执行结果:
没有遇到异常
1
try代码块中执行时没有异常就返回try代码块中的值1
那么如果try代码块中有异常呢?将会返回什么?
public class Test {
public static void main(String[] args) {
System.out.println(tryReturn());
}
public static int tryReturn() {
try {
int i=4/0;
System.out.println("没有遇到异常");
return 1;
} catch (Exception e) {
// TODO: handle exception
}finally {
}
return 2;
}
}
执行结果:
2
当执行try代码块遇到异常的时候,就会在终止执行,异常后面的代码不会被执行 另外,如果你在catch里写了return语句,则会执行catch中的return语句,如下:
public class Test {
public static void main(String[] args) {
System.out.println(tryReturn());
}
public static int tryReturn() {
try {
int i=4/0;
System.out.println("没有遇到异常");
return 1;
} catch (Exception e) {
// TODO: handle exception
return 3;
}finally {
}
return 2;//catch代码块中有return语句时 此处return代码不会被执行,且编译器会报错
//(实际上此处任何代码都不会被执行)
}
}
那么如果finally中有要执行的代码呢?return和finally中的代码谁先执行?
如下:
public class Test {
public static void main(String[] args) {
System.out.println(tryReturn());
}
public static int tryReturn() {
try {
int i=4/1;
System.out.println("没有遇到异常");
return 1;
} catch (Exception e) {
TODO: handle exception
System.out.println("执行catch代码块");
}finally {
System.out.println("执行finally代码块");
}
System.out.println("执行finally后的代码");
return 2;
}
}
执行结果:
没有遇到异常
执行finally代码块
1
当try中没有异常时就先执行finally中的代码,最后执行return 1 , 而且finally后面的System.out.println(“执行finally后的代码”);并没有被执行,显然,try中没有发生异常时,finally后的非return语句没有被执行
当上面try中有异常时执行结果是怎样的呢?
public class Test {
public static void main(String[] args) {
System.out.println(tryReturn());
}
public static int tryReturn() {
try {
int i=4/0;
System.out.println("没有遇到异常");
return 1;
} catch (Exception e) {
TODO: handle exception
System.out.println("执行catch代码块");
}finally {
System.out.println("执行finally代码块");
}
System.out.println("执行finally后的代码");
return 2;
}
}
执行结果:
执行catch代码块
执行finally代码块
执行finally后面的代码
2
如上,遇到异常后try代码块中发生异常后面的语句并没有被执行,而后执行catch中的代码,再先执行finally中的代码,最后执行finally后面的代码,并且finally后的非return语句也被执行了