2016-08-24 84 views
-1

我对Java相当陌生,无法理解try-catch-finally块中的控制流。无论何时在catch块中捕获到异常,catch块之后的代码也会被执行,无论是否将它放在finally块中。那么finally块的用处是什么?异常处理中的流程控制

class Excp 
{ 
public static void main(String args[]) 
{ 
    int a,b,c; 
    try 
    { 
    a=0; 
    b=10; 
    c=b/a; 
    System.out.println("This line will not be executed"); 
    } 
    catch(ArithmeticException e) 
    { 
    System.out.println("Divided by zero"); 
    } 
    System.out.println("After exception is handled"); 
} 
} 

如果我将最后一个print语句放在finally块中,没有区别。

+0

在'try'中抛出'new RuntimeException()',你会注意到catch块之后的代码没有被执行。然后添加一个finally块。 – Kayaman

+0

在发生任何异常之后,您可以使用'finally'模块将程序设置为可以使用的状态。 – Blobonat

+1

finally块**内的代码总是**执行,即使在try或catch中有一个return或一个未处理的异常。 这是解释[这里](https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html)这是一个非常简单的谷歌搜索。 **请使用谷歌。** –

回答

2

如果在try/catch块中发生另一个异常(由您的代码未处理),则会有所不同。

没有finally,最后一行不会被执行。使用finally时,代码无论如何都会执行。

这是特别有用的执行清理任务超出了垃圾收集器的覆盖范围:系统的ressource,数据库锁,文件删除等...

0

finally块也将执行,如果一个异常从catch抛出块,或者从try块中抛出不同的异常。

例子:

try { 
    int a=5; 
    int b=0; 
    int c=a/b; 
catch (NullPointerException e) { 
    // won't reach here 
} finally { 
    // will reach here 
} 

您也可以完全忽略catch块,仍然保证finally块将被执行:

try { 
    int a=5; 
    int b=0; 
    int c=a/b; 
} finally { 
    // will reach here 
} 
1

考虑一下:

try { 
    a=0; 
    b=10; 
    c=b/a; 
    System.out.println("This line will not be executed"); 
} 
catch(ArithmeticException e){ 
    throw new RuntimeException("Stuff went wrong", e); 
} 
System.out.println("This line will also not be executed"); 
0

的代码里面的finally块总是执行,偶数如果在trycatch中有return或未处理的异常。 这是解释here,它发现了一个非常简单的谷歌搜索。 请使用谷歌。

1

即使函数返回,也可以使用finally块来执行。

例如

public boolean doSmth() { 
    try { 
    return true; 
    } 
    finally { 
    return false; 
    } 
} 

会返回false;