javascript通行证
javascript中是否有类似python“pass”的东西 我想做与javascript等效的工作:javascript通行证,javascript,python,exception,exception-handling,Javascript,Python,Exception,Exception Handling,javascript中是否有类似python“pass”的东西 我想做与javascript等效的工作: try: # Something that throws exception catch: pass try: # Something that throws exception catch: pass 空块需要它,因为 try: # Something that throws exception catch: # continue other stuff 。
try:
# Something that throws exception
catch:
pass
try:
# Something that throws exception
catch:
pass
空块需要它,因为
try:
# Something that throws exception
catch:
# continue other stuff
。在JavaScript中,您可以只使用一个空的catch
块
try {
// Something that throws exception
}
catch (e) {}
有,这是: 我想做与javascript等效的工作:
try:
# Something that throws exception
catch:
pass
try:
# Something that throws exception
catch:
pass
Python没有try/catch。它已经试过了。因此,将catch
替换为except
,我们将有以下内容:
try {
// throw any exception
} catch(err) {}
捕获后的空代码块相当于Python的pass
最佳实践
然而,人们对这个问题的理解可能有点不同。假设您希望采用与Python try/except块相同的语义。Python的异常处理更加细致,允许您指定捕获哪些错误
事实上,只捕获特定错误类型被认为是最佳实践
因此,Python的最佳实践版本是,因为您只希望捕获准备处理的异常,并避免隐藏bug:
try:
raise TypeError
except TypeError as err:
pass
您可能应该对适当的错误类型进行子类化,因为标准Javascript没有非常丰富的异常层次结构。我选择了TypeError
,因为它的拼写和语义与Python的TypeError
相同
为了在Javascript中遵循相同的语义,我们首先要做的是,因此我们需要对控制流进行调整。因此,我们需要确定错误是否不是我们希望通过if条件传递的错误类型。缺少else控制流是使类型错误静音的原因。理论上,有了这个代码,所有其他类型的错误都应该浮出水面并被修复,或者至少被识别以进行额外的错误处理:
try { // try:
throw TypeError() // raise ValueError
} catch(err) { // # this code block same behavior as
if (!(err instanceof TypeError)) { // except ValueError as err:
throw err // pass
}
}
欢迎评论 空牙套没用?顺便说一句,默默地吃异常几乎总是错误的。对于Adam的观点,我对这个老问题有了一个新的答案,该答案针对Python下面微妙的错误处理进行了调整:eslint
对此表示不满。