什么时候执行?

Van*_*nel 8 java android try-catch

我有这个嵌套try的java代码:

try
{   
    try
    {
        [ ... ]
    {
    catch (Exception ex)
    {
        showLogMessage(ex);
        return;
    }

    while (condition == true)
    {
        try
        {
            [ ... ]
        {
        catch (Exception ex)
        {
            showLogMessage(ex);
            continue;
        }

        [ ... ]
    }
}
catch (NumberFormatException e)
{
    showLogMessage(e);
}
finally
{
    doSomeThingVeryImportant();
}
Run Code Online (Sandbox Code Playgroud)

我想知道finally当我得到异常时是否总是执行.我问这个因为catch块有return或有continue声明.

什么时候doSomeThingVeryImportant()执行?当我得到一个Exception时,我NumberFormatException什么时候开始?

我只想要在执行任何catch块之后,也执行finally块.

Jai*_*dra 20

finally块(如果使用的话)放在try块和后面的catch块之后.finally块包含将运行的代码,无论是否在try块中抛出异常.一般语法如下所示:

public void someMethod{
   Try {
   // some code
   }

   Catch(Exception x) {
   // some code
   }

   Catch(ExceptionClass y) {
   // some code
   }

   Finally{
   //this code will be executed whether or not an exception 
   //is thrown or caught
   }
}
Run Code Online (Sandbox Code Playgroud)

这里有4种可能的情况:

  1. try块运行到最后,不会抛出任何异常.在这种情况下,finally块将在try块之后执行.

  2. try块中抛出异常,然后在其中一个catch块中捕获.在这种情况下,finally块将在catch块执行后立即执行.

  3. try块中抛出异常,并且方法中没有匹配的catch块可以捕获异常.在这种情况下,对方法的调用结束,异常对象被抛出到封闭方法 - 就像try-catch-finally块所在的方法一样.但是,在方法结束之前,执行finally块.

  4. 在try块运行完成之前,它将返回到调用方法的任何位置.但是,在它返回到调用方法之前,finally块中的代码仍然执行.所以,请记住,即使try块中某处有return语句,finally块中的代码也会被执行.

更新:最后总是执行,无论try或catch块发生什么(失败,返回,异常,完成等).

  • 这应该是正确的答案 (2认同)

tos*_*tao 6

The finally block always executes when the try block exits点击)。