为什么在 JavaScript 中不经常使用 Try/Catch?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12609527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:39:43  来源:igfitidea点击:

Why isn't Try/Catch used more often in JavaScript?

javascript

提问by Darrell Brogdon

It seems like with other languages that support Try/Catch, developers make use of that feature more than they do in JavaScript. Is there a reason for this? Is the JS implementation of Try/Catch flawed?

对于支持 Try/Catch 的其他语言,开发人员似乎比在 JavaScript 中更多地使用该功能。是否有一个原因?Try/Catch 的 JS 实现是否有缺陷?

采纳答案by Chase

Try taking a look at this article: http://dev.opera.com/articles/view/efficient-javascript/?page=2#trycatch

试着看看这篇文章:http: //dev.opera.com/articles/view/efficient-javascript/?page=2#trycatch

From the above link:

从上面的链接:

The try-catch-finally construct is fairly unique. Unlike other constructs, it creates a new variable in the current scope at runtime. This happens each timethe catch clause is executed, where the caught exception object is assigned to a variable. This variable does not exist inside other parts of the script even inside the same scope. It is created at the start of the catch clause, then destroyed at the end of it.

try-catch-finally 结构相当独特。与其他构造不同,它在运行时在当前作用域中创建一个新变量每次执行 catch 子句时都会发生这种情况,其中捕获的异常对象被分配给一个变量。即使在同一范围内,该变量也不存在于脚本的其他部分。它在 catch 子句开始时创建,然后在它结束时销毁。

Because this variable is created and destroyed at runtime, and represents a special case in the language, some browsers do not handle it very efficiently, and placing a catch handler inside a performance critical loop may cause performance problems when exceptions are caught.

因为这个变量是在运行时创建和销毁的,并且代表了语言中的一种特殊情况,所以一些浏览器不能非常有效地处理它,并且在捕获异常时将捕获处理程序放置在性能关键循环中可能会导致性能问题

You can also view a similar question here

您也可以在这里查看类似的问题

UPDATE

更新

Adding a link to: https://github.com/petkaantonov/bluebird/wiki/Optimization-killersas it contains useful information regarding V8 and how it handles these (and similar) constructs.

添加一个链接到:https: //github.com/petkaantonov/bluebird/wiki/Optimization-killers,因为它包含有关 V8 的有用信息以及它如何处理这些(和类似的)结构。

In particular:

特别是:

Currently not optimizable:

目前不可优化:

  • Generator functions
  • Functions that contain a for-of statement
  • Functions that contain a try-catch statement
  • Functions that contain a try-finally statement
  • Functions that contain a compound let assignment
  • Functions that contain a compound const assignment
  • Functions that contain object literals that contain proto, or get or set declarations.
  • 发电机功能
  • 包含 for-of 语句的函数
  • 包含 try-catch 语句的函数
  • 包含 try-finally 语句的函数
  • 包含复合 let 赋值的函数
  • 包含复合常量赋值的函数
  • 包含包含proto或 get 或 set 声明的对象字面量的函数。

Likely never optimizable:

可能永远无法优化:

  • Functions that contain a debugger statement
  • Functions that call literally eval()
  • Functions that contain a with statement
  • 包含调试器语句的函数
  • 直接调用 eval() 的函数
  • 包含 with 语句的函数

回答by MicronXD

No it's not flawed, but for synchronous code it's typically easier and cleaner to check things with your own code than use a clunky try{}catch(e){}.

不,它没有缺陷,但对于同步代码,使用自己的代码检查事物通常比使用笨重的try{}catch(e){}.

example:

例子:

var container = document.getElementById("timmy");
container.innerHTML = "I'm timmy!";

If there's no element whose ID is "timmy", we can handle that either like this:

如果没有 ID 为“timmy”的元素,我们可以这样处理:

try
{
    container.innerHTML = "I'm timmy";
}
catch (error)
{
    //handle no container
}

or:

或者:

if(container) container.innerHTML = "I'm timmy";
else //handle no container


Another thing to keep in mind is JavaScript applications are event-driven and try/catch blocks in the main part of your program can't catch errors that occur in event callbacks.

要记住的另一件事是 JavaScript 应用程序是事件驱动的,程序主要部分中的 try/catch 块无法捕获事件回调中发生的错误。

example:

例子:

sqlConnection.query("SELECT * FROM table", 
    function(){console.log("queried!");});

that will trigger some native code that runs as your program continues. If an error occurs, you can't expect your program to back-track up to this line so your error handler can do its stuff! Instead, you handle errors in the call-back itself. It is common practice to provide callbacks with any error that occurred by passing it as the first parameter.

这将触发一些随着您的程序继续运行而运行的本机代码。如果发生错误,您不能指望您的程序回溯到这一行,以便您的错误处理程序可以完成它的工作!相反,您在回调本身中处理错误。通常的做法是通过将其作为第一个参数传递而为发生的任何错误提供回调。

sqlConnection.query("SELECT * FROM table", 
    function(error, data){
        if(error) console.log("query failed");
        else console.log("queried!");
    });

Alternatively, if your code fails in a callback, you can handle it the way I mentioned above.

或者,如果您的代码在回调中失败,您可以按照我上面提到的方式处理它。

link.onclick = function(e)
{
    var popUp = document.getElementById("popup");
    if(!popUp)
        return true; //follow link if no pop-up exists
    popUp.style.display = "block";
};

回答by Sruly

The async nature of most javascript code hides the try/catch at a low level and then calls an error callback.

大多数 javascript 代码的异步性质将 try/catch 隐藏在低级别,然后调用错误回调。

Most heavy code in js is async and uses a callback or promise pattern. The other code is simple and does not require try/catch.

js 中最繁重的代码是异步的,并使用回调或承诺模式。其他代码很简单,不需要 try/catch。

If you dig into js libraries (pick your favorite) you will find the try/catch blocks that wrap much of the heavy app code that executes in modern js applications. These libraries then call the error or fail callback that you see in many js code samples.

如果你深入研究 js 库(选择你最喜欢的),你会发现 try/catch 块包含了在现代 js 应用程序中执行的大部分繁重的应用程序代码。这些库然后调用您在许多 js 代码示例中看到的错误或失败回调。

回答by Cruril

I believe that there is more overhead with a try/catch as opposed to an if statement, although i think it only matter when the exception is actually thrown. I use try/catches often, but only if I know there will be a good chance an exception could be thrown.

我相信与 if 语句相比,try/catch 有更多的开销,尽管我认为只有在实际抛出异常时才重要。我经常使用 try/catch,但前提是我知道很有可能会抛出异常。

If used efficiently there is really no reason to not use a try/catch.

如果有效地使用,真的没有理由不使用 try/catch。

回答by geekman

JavaScript doesn't need them much, the reason is, there is hardly any reason to catch errors, because, one error does not stop the entire script. Javascript is event driven, most functions run when a specific event occurs, and it is client side, so if anything goes wrong, it goes wrong, catching and handling the error would be hardly any beneficial. only my view.

JavaScript 并不需要它们,原因是,几乎没有任何理由捕获错误,因为一个错误并不会停止整个脚本。Javascript 是事件驱动的,大多数函数在特定事件发生时运行,而且它是客户端,所以如果出现任何问题,它就会出错,捕获和处理错误几乎没有任何好处。只有我的看法。