try{}catch{}finally{}代码块里面都有return:
public class DemoTest {
public static void main(String[] args) {
int num = getNum();
System.out.println("执行结果: " +num);
}
public static int getNum() {
int i;
try {
i = 8;
System.out.println("try块中的i的值: "+i);
int a = 90 / 0;
return i;
} catch (Exception e) {
System.out.println(e.getMessage());
i = 5;
return i;
} finally {
// finally中的代码一定会执行
System.out.println("执行finally~~~");
i = 6666;// 此处重新给i赋值
System.out.println("finally 块中的值: "+i);
return i;// 无论如何总会在此处返回i的值
}
}
}
执行结果:
无论是否发生异常总是返回finally中的值.
return在try{}catch{}代码块里面,finally{}代码块中没有return:
public class DemoTest {
public static void main(String[] args) {
int num = getNum();
System.out.println("执行结果: " +num);
}
public static int getNum() {
int i;
try {
i = 8;
System.out.println("try块中的i的值: "+i);
// int a = 90 / 0;
return i;// 没有异常会在此处返回i的值
} catch (Exception e) {
System.out.println(e.getMessage());
i = 5;
return i;// catch了异常之后会在此处返回i的值
} finally {
// finally中的代码一定会执行
System.out.println("执行finally~~~");
i = 6666;// 此处重新给i赋值
System.out.println("finally 块中的值: "+i);
}
}
}
执行结果:
1,没有异常,返回try块中的值.
2,发生异常,返回catch中的值.
return在catch{}块里面和在try{}catch{}finally{}代码块外面:
public class DemoTest {
public static void main(String[] args) {
int num = getNum();
System.out.println("执行结果: " +num);
}
public static int getNum() {
int i;
try {
i = 8;
System.out.println("try块中的i的值: "+i);
int a = 90 / 0;
} catch (Exception e) {
System.out.println(e.getMessage());
i = 5;
return i;// catch了异常之后会在此处返回i的值
} finally {
// finally中的代码一定会执行
System.out.println("执行finally~~~");
i = 6666;// 此处重新给i赋值
System.out.println("finally 块中的值: "+i);
}
return i;// 没有异常返回此处的值
}
}
执行结果:
1,catch住异常之后返回catch{}块中的值.
2,没有异常不会执行catch{}块中的代码,会执行到最后,返回最后的值.
总结:
1,只要finally{}块中有return则一定会返回finally{}块中的值.
2,catch{}块中有return和在finally{}代码块后面有return,执行结果catch住异常之后会直接返回catch{}中的值,没有异常的话会执行最后返回最后的值.