什么时候应该在 JavaScript 中使用 try/catch?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7148019/
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-25 23:06:19  来源:igfitidea点击:

When should you use try/catch in JavaScript?

javascripttry-catch

提问by Sanghyun Lee

When I'm developing normal web application with JavaScript, the try/catchstatement is not needed usually. There's no checked exception, File IO or database connection in JavaScript.

当我使用 JavaScript 开发普通的 Web 应用程序时,try/catch通常不需要该语句。JavaScript 中没有检查异常、文件 IO 或数据库连接。

Is try/catchstatement useful in JavaScript? When can I use it?

try/catch声明在JavaScript有用吗?我什么时候可以使用它?

采纳答案by Quentin

Use it whenever code you are running might throw an exception. Remember that you can throwyour own errors — most of the try…catchstuff I use is for catching my own exceptions.

每当您正在运行的代码可能引发异常时使用它。请记住,您可以创建throw自己的错误——try…catch我使用的大部分内容都是用于捕获我自己的异常。

回答by Saeed Neamati

try...catchblocks are generally encourages to be used less, and this doesn't depend on the language you use.

try...catch通常鼓励少使用块,这与您使用的语言无关。

The main reason for this is the cost of catchblocks. Also another reason is that, when you wrap many statements with a single try...catchblock, in catchblock you can't be sure what was exactly the main problem.

造成这种情况的主要原因是catch区块的成本。另一个原因是,当您用单个try...catch块包装许多语句时,在catch块中您无法确定主要问题到底是什么。

It's better to use techniques like input validation or if...elseblocks to reduce the probability of an exception (error) to happen. For example, when you want to work with a number which is taken from user, instead of using try...catch, you can use:

最好使用输入验证或if...else块等技术来降低发生异常(错误)的可能性。例如,当您想使用从用户那里获取的数字时try...catch,您可以使用:

if (isNaN(numberVariable))
{
    alert('you should enter a valid number');
}

回答by parliament

One scenario I find try/catch/finally useful is with deeply nested objects where a null can pop up at any level. for example, consider this:

我发现 try/catch/finally 有用的一个场景是深度嵌套的对象,其中 null 可以在任何级别弹出。例如,考虑这个:

var something = one.two.three.four.five;

to perform this "get" with 100% safety one would have to write a bit of verbose code:

要以 100% 的安全性执行此“获取”,必须编写一些冗长的代码:

if(one && one.two && one.two.three && one.two.three.four)
   something = one.two.three.four.five;

Now imagine the variable names are realistic and longer and you quickly get a very ugly code if statement.

现在想象变量名是现实的和更长的,你很快就会得到一个非常难看的代码 if 语句。

I tend to use try/catch/finally to simplify this when I don't care about any "else" scenarios and just want the object or not:

当我不关心任何“其他”场景并且只想要对象或不想要对象时,我倾向于使用 try/catch/finally 来简化这一点:

var something;
try { something = one.two.three.four.five; }
catch { something = "default"; }
finally { doSomething(something); }

回答by luongnv89

I found this from a post here:

我从这里帖子中找到了这个:

When Should You Use try-catch?

什么时候应该使用 try-catch?

The try-catch statement should be used any time you want to hide errors from the user, or any time you want to produce custom errors for your users' benefit. If you haven't figured it out yet, when you execute a try-catch statement, the browser's usual error handling mechanism will be disabled.

任何时候你想对用户隐藏错误,或者任何时候你想为用户的利益产生自定义错误时,都应该使用 try-catch 语句。如果你还没有搞清楚,当你执行 try-catch 语句时,浏览器通常的错误处理机制将被禁用。

You can probably see the possible benefits to this when building large applications. Debugging every possible circumstance in any application's flow is often time consuming, and many possibilities could be inadvertantly overlooked. Of course, with proper bug testing, no area should be overlooked. But the try-catch statement works as a nice fallback in areas of your code that could fail under unusual circumstances that were not foreseen during development.

在构建大型应用程序时,您可能会看到这可能带来的好处。调试任何应用程序流程中的每一种可能情况通常都很耗时,并且可能会无意中忽略许多可能性。当然,通过适当的错误测试,任何区域都不应被忽视。但是 try-catch 语句在您的代码区域中作为一个很好的后备,在开发过程中没有预见到的异常情况下可能会失败。

Another benefit provided by the try-catch statement is that it hides overly-technical error messages from users who wouldn't understand them anyhow.

try-catch 语句提供的另一个好处是,它向那些无论如何都不会理解它们的用户隐藏了过于技术性的错误消息。

The best time to use try-catch is in portions of your code where you suspect errors will occur that are beyond your control, for whatever reasons.

使用 try-catch 的最佳时间是在您怀疑会发生超出您控制范围的错误的代码部分,无论出于何种原因。

When Should try-catch be Avoided?

什么时候应该避免try-catch?

You shouldn't use the try-catch statement if you know an error is going to occur, because in this case you would want to debug the problem, not mask it. The try-catch statement should be executed only on sections of code where you suspect errors might occur, and due to the overwhelming number of possible circumstances, you cannot completely verify if an error will take place, or when it will do so. In the latter case, it would be appropriate to use try-catch.

如果您知道将要发生错误,则不应使用 try-catch 语句,因为在这种情况下,您希望调试问题,而不是掩盖问题。try-catch 语句应该只在您怀疑可能发生错误的代码部分执行,并且由于可能发生的情况太多,您无法完全验证是否会发生错误,或者何时会发生。在后一种情况下,使用 try-catch 是合适的。

回答by Michael Berkowski

External Javascript libraries and widgets often make use of exceptions for instantiation errors. It's common to need to:

外部 Javascript 库和小部件通常使用实例化错误的异常。通常需要:

try {
  var w = new Widget();
}
catch (e) {
  // widget failed
}

回答by Thor Jacobsen

Well, I personally (mis?)use it, when I write some code which I'm not sure will execute properly, but the user don't need to know about the error.

好吧,我个人(错误?)使用它,当我编写一些我不确定会正确执行的代码时,但用户不需要知道错误。

Other than that, I've been using it on some user controls, to which you can define an 'action' property in your HTML markup, and the javascript will try executing that action, like this:

除此之外,我一直在一些用户控件上使用它,您可以在 HTML 标记中定义一个“action”属性,javascript 将尝试执行该操作,如下所示:

try{
     window['method'](args);
}catch(e){
     try{
         window['optionalExceptionHandler'](e, args);
     }catch(e){ return; }
}

(I like to think it's better than eval()xD)

(我喜欢认为它比eval()xD更好)