finally语句的用途 [英] Uses of the finally statement

查看:36
本文介绍了finally语句的用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题.在Java中,我使用finally语句来关闭资源,因为这是一个好习惯".几年来,我一直在用Javascript开发,然后在Node.js中开发,我从不从未使用过 finally 语句.我知道在Node.js中,我们所有人都遵循 first参数错误处理模式.无论如何,以下2个摘要都执行相同的操作:

This is a very basic question. In Java I use the finally statement to close resources because "it's a good practice". I've been developing in Javascript and then in Node.js during some years and I've never used the finally statement. I know that in Node.js all of us follow the first parameter error handling pattern. Anyway, the 2 following snippets do the same:

try{
    throw 123
}catch (e){

}finally{
    console.log(1)
}

.

try{
    throw 123
}catch (e){

}

console.log(1)

两个都打印1.

为什么 finally (如果没有真正的好处)是关键字?可以将清除代码放在捕获中.

Why is finally a keyword if it has no real benefit? The clean up code can be put inside the catch.

推荐答案

最终不仅对异常处理有用,它还使程序员避免因返回,继续或中断而意外跳过清理代码.

finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.

一个简单而直接的例子说明了差异.有一个 return 中断了函数的完成,但是在 finally 中的 console.log 被调用,而最后一个 console.log 被跳过.

Just a simple and straightforward example that shows the difference. There is a return that breaks the function completion, but the console.log in finally is called while the last console.log is skipped.

let letsTry = () => {

  try {
    // there is a SyntaxError
    eval('alert("Hello world)');
    
  } catch(error) {
    console.error(error);
	
    // break the function completion
    return;
  } finally {
      console.log('finally')
  }

  // This line will never get executed
  console.log('after try catch')
}

letsTry();

这篇关于finally语句的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆