如果finally有return语句,永远返回finally中的结果,避免该情况.
正常情况
package cn.itcast.test;
public class TryTest8 {
public static void main(String[] args) {
int value = show(0);
System.out.println("value = " + value);
}
public static int show(int x)
{
try
{
if(x==0){
throw new Exception("x是零");
}
System.out.println("try.....");
return 1;
}catch(Exception e)
{
e.printStackTrace();
System.out.println("捕获异常");
return 2;
}finally
{
System.out.println("必须执行");
//return 3;
}
}
}
finally中加了return
- 永远都是返回finally中的结果
package cn.itcast.test;
public class TryTest8 {
public static void main(String[] args) {
int value = show(0);
System.out.println("value = " + value);
}
public static int show(int x)
{
try
{
if(x==0){
throw new Exception("x是零");
}
System.out.println("try.....");
return 1;
}catch(Exception e)
{
e.printStackTrace();
System.out.println("捕获异常");
return 2;
}finally
{
System.out.println("必须执行");
return 3;
}
}
}