最后进入异常处理

发布于 2024-08-26 19:06:42 字数 44 浏览 6 评论 0原文

异常处理中的finally 块到底执行什么操作?

What exactly does a finally block in exception handling perform?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

心作怪 2024-09-02 19:06:42

它保存应该始终执行的代码,无论是否发生异常。

例如,如果你打开了一个文件,你应该在finally块中关闭它,以确保它始终被关闭;如果您在 try 块中关闭它,则较早的异常将导致执行直接跳转到 catch 块并跳过关闭文件。

有关更多详细信息,请参阅 Java 教程

It holds code that should always be executed, regardless of whether an exception occurs.

For example, if you have opened a file, you should close it in the finally block to ensure that it will always be closed; if you closed it in the try block, an earlier exception would cause execution to jump straight to the catch block and skip closing the file.

See the Java tutorials for more details.

如若梦似彩虹 2024-09-02 19:06:42

无论是否抛出异常,finally 块始终都会执行。我能想到的经典使用示例是关闭文件。

FileOutputStream stream = null;
try{
    // do stuff with the stream here
} catch (IOException ex){
    // handle exception
} finally{
    // always close the stream
    if(stream != null){
        stream.close();
    }
}

The finally block always executes, regardless of whether or not the exception was thrown. The classic use example I can think of is closing files.

FileOutputStream stream = null;
try{
    // do stuff with the stream here
} catch (IOException ex){
    // handle exception
} finally{
    // always close the stream
    if(stream != null){
        stream.close();
    }
}
一张白纸 2024-09-02 19:06:42

无论您是否进入 catch 块,它都会执行,这意味着这是处理对象和进行其他清理的好地方。

It executes no matter if you get into the catch block or not, meaning that is a great place for disposing of objects and doing other cleanups.

无畏 2024-09-02 19:06:42

当代码块中有多个 return 语句时,我经常使用它来清理开放资源,从而使代码更加干净,因为您不需要在每个 return 语句之前克隆相同的“关闭资源”代码。即使您在 try 部分中执行了返回,也可以保证代码将调用 finally 部分。在这种情况下,它还有助于提高代码安全性,因为程序员很容易意外地将其遗漏。

I use it a lot for cleaning up open resources when there are multiple return statements in a block of code, making the code a lot cleaner as you don't need to clone the same 'close resource' code before every return statement. It's guaranteed that the code will call the finally section, even if you do a return within the try section. It also helps with code safety in this instance, since the programmer could easily leave it out by accident.

2024-09-02 19:06:42

如果您在 trycatch 块以及 finally 块中返回一个值,请记住 finally< /code> 块的返回值就是您最终得到的值(最后执行的块)。这意味着如果您尝试一些不会抛出Exception并且应该返回一个值的代码,但您的finally块也应该返回一个值,finally 块的值就是实际返回的值。 这个SO线程讨论了这一点。我不认为在 trycatch 中返回值通常是必要的或最好的主意。另请注意,System.exit(0) 会终止 JVM,从而在其他任何操作运行之前停止执行,这可能会导致您的 finally 块未执行。

If you return a value in your try or catch block as well as in the finally block, keep in mind that the finally block's return value is what you'll end up with (the last block executed). That means if you try some code that does NOT throw an Exception and is supposed to return a value, but your finally block is also supposed to return a value, the finally block's value is what will actually be returned. This SO thread talks about that very point. I don't believe returning a value inside a try or catch is usually necessary or the best idea. Also note that System.exit(0) kills the JVM and thus halts execution before anything else runs, which might render your finally block unexecuted.

仅一夜美梦 2024-09-02 19:06:42

finally 块主要用于执行关闭语句,例如 con.close ,即关闭与数据库的连接....try 块后面总是跟随 catch 块或finally(或两者)..如果你一旦进入try块,那么你的finally块肯定会被执行,除了系统错误,finally块中的异常。...finally块的主要关键点是它总是被执行,即使是异常是否被处理..

finally block is mainly used to perform close statement for example con.close that is to close connection from database....try block is always followed by either catch block or finally (or both also)...If you once entered in the try block then your finally block will be definately execute except system error,exception in finally block....Main key point of finally block is that it always be executed even the exception is handled or not..

诗酒趁年少 2024-09-02 19:06:42

使用finally关键字只是为了确保finally块中的代码必须在所有情况下执行,无论是否发生异常。

例如:

 try{
     }
     catch(Exception e){
     }
      finally{
             System.out.print("finally executed");
            }

注意:在上述情况下,finally 总是会执行。

finally keyword is used just to make sure that code present in finally block must execute in all circumstances irrespective of exception occurances.

for eg:

 try{
     }
     catch(Exception e){
     }
      finally{
             System.out.print("finally executed");
            }

Note: In above case finally will always execute.

静赏你的温柔 2024-09-02 19:06:42

尽管已经有很多答案给出了 finally 块在所有条件下都需要执行某些代码,无论是由于异常而中断,还是一些错误的代码,或者您返回了程序控制权流程来自 try 块,这里我添加一个示例来解释 finally 块的需要;

假设您向朋友借了一支笔。你使用它然后返回(我认为你是一位绅士)。现在无论发生什么,你都必须归还笔。你可以处理各种情况,并将最不可避免的情况放在finally块中。

//Borrow the pen
try{
  //Use the pen
}catch(StolenPen how){
  //Buy new pen
}catch(InkFinished how){
  //Refill the pen
}catch(SomethingWrong how){
  //Buy new pen
}finally{
  //Return new pen
}

Though there are many answers have already given that finally block is required to execute some piece of code in all the conditions whether there is some interruption due to exception, or some bad code, or you return the program control flow from try block, Here I'm adding an example to explain the need of finally block;

Let's suppose you have borrowed a pen from your friend. You use it and then return ( I consider you a gentleman). Now whatever happens, you have to return the pen. You can handle various situations and you put most unavoidable condition in finally block.

//Borrow the pen
try{
  //Use the pen
}catch(StolenPen how){
  //Buy new pen
}catch(InkFinished how){
  //Refill the pen
}catch(SomethingWrong how){
  //Buy new pen
}finally{
  //Return new pen
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文