本文介绍了Javascript中的try-catch语句捕获了哪些类型的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写

try { null = foobar } catch(e) { alert( e ) };

没有任何警报,但 ReferenceError 是登录控制台。但是,

nothing is alerted, but a ReferenceError is logged in the console. However,

try { barfoo = foobar } catch(e) { alert( e ) };

显示带有 ReferenceError 的警报。

所以问题是:try-catch语句捕获了什么类型的错误?

So the question is: what types of errors in what context get caught by try-catch statements?

推荐答案

因此,您的第一行代码是无效的JavaScript语法。这就是为什么你得到一个:

ReferenceError:赋值中的左侧无效(你不能将变量分配给 null

So, your first line of code is invalid JavaScript syntax. That's why you're getting a:
ReferenceError: Invalid left-hand side in assignment (You can't assign vars to null)

您的第二行是有效语法,但抛出:

ReferenceError :foobar未定义

Your second line is valid syntax, but throws a:
ReferenceError: foobar is not defined.

现在,第二行被捕获的原因,但第一行没有,是因为JavaScript解释器在解释代码时抛出第一个错误,比较当它实际执行时,在第二个例子中。

Now, the reason the second line does get caught, but the first one doesn't, is because the JavaScript interpreter is throwing the first error when interpreting the code, compared to when it's actually executing it, in the second example.

一个更简单的解释,由:

A more simple explanation, courtesy of @Matt:

您可以将其视为JavaScript解释器,在执行它之前查看所有代码并思考这一切都正确解析?如果没有,它会抛出一个无法捕获的错误(无论是 SyntaxError 还是 ReferenceError )。否则,代码将被执行,并且在某一时刻你在执行期间输入 try / catch块,并且在被捕获时抛出任何运行时错误。

You can sort of thinking it as the JavaScript interpreter looking at all the code before it executes it and thinking does that all parse correctly? If it doesn't, it throws an uncatchable Error (be it a SyntaxError or ReferenceError). Otherwise, the code beings to execute, and at one point you enter the try/catch block during execution and any runtime errors thrown whilst in there are caught.

这篇关于Javascript中的try-catch语句捕获了哪些类型的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 00:47