Error handling 哪种错误处理模式更好:一个try/catch围绕大代码块,另一个try/catch围绕小代码块?

Error handling 哪种错误处理模式更好:一个try/catch围绕大代码块,另一个try/catch围绕小代码块?,error-handling,Error Handling,这是一个关于风格的问题。以下哪种模式是处理错误的更好方法 模式#1: 模式2: 我发现模式#1更加具体,您可以准确地记录错误发生的位置/原因(即“function1()抛出错误…”)。诚然,您可以依赖err中的错误消息,但这并不总是有用的(例如,“cannotreference prop of undefined”不会告诉您来自哪个函数) 另一方面,模式#2更简洁(即更少的代码,更容易维护),但以特定性为代价 一种模式优于另一种模式是有原因的,还是仅仅是个人偏好的问题?通常,我打破我的“尝试/捕

这是一个关于风格的问题。以下哪种模式是处理错误的更好方法

模式#1:

模式2:

我发现模式#1更加具体,您可以准确地记录错误发生的位置/原因(即“function1()抛出错误…”)。诚然,您可以依赖err中的错误消息,但这并不总是有用的(例如,“cannotreference prop of undefined”不会告诉您来自哪个函数)

另一方面,模式#2更简洁(即更少的代码,更容易维护),但以特定性为代价


一种模式优于另一种模式是有原因的,还是仅仅是个人偏好的问题?

通常,我打破我的“尝试/捕捉”想法只是为了阅读澄清,类似于函数。这两种方法的运行速度几乎相同,因此为了提高效率,这两种方法都是可以接受的。最好是将错误具体化。我的try/catch块通常看起来像

try {
    function1();
    function2();
    function3();
} catch (err1) {
    console.log(‘The following error was thrown:’, err);
} catch (err2) {
    console.log(‘The following error was thrown:’, err);
} catch (all) {
    console.log(‘The following error was thrown:’, err);
}

用合理的解释支持你的用法
Try {
  function1();
  function2();
  function3();
} catch (err) {
  console.log(‘The following error was thrown:’, err);
}
try {
    function1();
    function2();
    function3();
} catch (err1) {
    console.log(‘The following error was thrown:’, err);
} catch (err2) {
    console.log(‘The following error was thrown:’, err);
} catch (all) {
    console.log(‘The following error was thrown:’, err);
}