异常处理是大多数编程语言需要遇到的问题,java中的try-catch块和C++差不多,但是java中却多了一个finally块。这个块无论异常是否发生都会执行。但是如果在try块中或者在catch块中有return 语句,那会先执行return语句吗?答案是否定的,程序会先执行finally语句块,然后再执行try块或catch块的return语句(这里先假设finally块中没有return语句,finally块中有return语句的下面再讨论)。例如以下程序,函数f()没有抛出异常,在函数testFinally()中会先执行f(),然后执行finally块中的输出语句,然后执行try块的return 1 语句。
public class Test
{
public void f() throws Exception
{
System.out.println("function: f()");
}
public int testFinally()
{
try
{
f();
return 1;
}
catch (Exception e)
{
System.out.println(e.getMessage());
return -1;
}
finally
{
System.out.println("testFinally(): finally");
}
}
public static void main(String[] args)
{
Test test = new Test();
int result = test.testFinally();
System.out.println("result of function testFinally : " + result);
}
}
程序输出结果如下图所示
以下程序在f()函数会抛出异常,在testFinally() 函数中捕获抛出的异常进入catch块输入异常信息,然后进入finally块执行输出语句,再回到catch块执行retrun 语句
public class Test
{
public void f() throws Exception
{
System.out.println("function: f()");
throw new Exception("Exception in function f()");
}
public int testFinally()
{
try
{
f();
return 1;
}
catch (Exception e)
{
System.out.println(e.getMessage());
return -1;
}
finally
{
System.out.println("testFinally(): finally");
}
}
public static void main(String[] args)
{
Test test = new Test();
int result = test.testFinally();
System.out.println("result of function testFinally : " + result);
}
}
程序输入结果如下图所示:
以上讨论了try-catch块中有return语句而finally块中没有return语句的情况,接下来讨论三者都有return语句的情况。当finally块中有return语句时,程序执行到return语句会跳出函数,所以就不会再执行try块或catch块中的return语句了。例如以下两个程序中,函数testFinally()返回的结果都是100而不是1或者-1.
public class Test
{
public void f() throws Exception
{
System.out.println("function: f()");
}
public int testFinally()
{
try
{
f();
return 1;
}
catch (Exception e)
{
System.out.println(e.getMessage());
return -1;
}
finally
{
System.out.println("testFinally(): finally");
return 100;
}
}
public static void main(String[] args)
{
Test test = new Test();
int result = test.testFinally();
System.out.println("result of function testFinally : " + result);
}
}
程序执行结果如下图:
抛出异常的finally块有return语句的程序
public class Test
{
public void f() throws Exception
{
System.out.println("function: f()");
throw new Exception("Exception in function f()");
}
public int testFinally()
{
try
{
f();
return 1;
}
catch (Exception e)
{
System.out.println(e.getMessage());
return -1;
}
finally
{
System.out.println("testFinally(): finally");
return 100;
}
}
public static void main(String[] args)
{
Test test = new Test();
int result = test.testFinally();
System.out.println("result of function testFinally : " + result);
}
}
程序执行结果如下图所示:
综上所述:如果try-catch块有return语句,当finally块没有return语句时,先执行finally块再执行try-catch块中的return语句,当finally块中有return语句时,不会再执行try-catch块中的return语句