关键区别:抛出异常会停止执行,而console.error
则不会。
大多数情况下,最好抛出一个错误。
这是一种内置的方法来表示某些操作失败了,如果错误没有被预期、捕获和妥善处理,正常的执行将无法继续。
在大多数平台上,未捕获的异常也会被记录到控制台中以警告开发人员,但已捕获的异常不会被记录,因为它们被认为已被代码处理。
在错误发生但不致命的情况下使用console.error
可以提醒开发人员。
然而,过度使用此功能很容易导致其他错误和更难调试的代码。例如,请考虑以下代码:
const elem = document.querySelector('.elem')
if(!elem)
console.error('elem cannot be found!')
const returnValue = functionThatDoesSomethingWithElem(elem)
if(!returnValue.success)
console.error('Doing something with elem has failed!')
if(!returnValue.doSomethingElse())
console.error('Doing something else with elem has failed!')
如果没有elem,上面的代码将会记录三个错误,但是执行仍然会继续,可能会导致更多的错误。通过抛出异常,可以避免这种情况:
const elem = document.querySelector('.elem')
if(!elem)
throw new Error('elem cannot be found!')
const returnValue = functionThatDoesSomethingWithElem(elem)
if(!returnValue.success)
throw new Error('Doing something with elem has failed!')
if(!returnValue.doSomethingElse())
throw new Error('Doing something else with elem has failed!')
如果您不将其放入 try..catch
结构中,这将仅打印第一个错误消息,并停止执行,例如:
try{
const elem = document.querySelector('.elem')
if(!elem)
throw new Error('elem cannot be found!')
const returnValue = functionThatDoesSomethingWithElem(elem)
if(!returnValue.success)
throw new Error('Doing something with elem has failed!')
if(!returnValue.doSomethingElse())
throw new Error('Doing something else with elem has failed!')
}catch(exception){
console.error(exception)
fallbackMethod()
}
另外还有一个不同之处:throw
的错误可以被函数的调用者捕捉到,因此可以通过编程方式处理它们(使执行继续,并且不显示错误)。另一方面,如果使用console.error
,调用者无法确定错误是否是预期的,这会导致即使错误是正常的,也会记录错误,因此控制台可能变得混乱(您无法确定哪些是真正的错误,哪些不是)。