gpt4 book ai didi

error-handling - 哪种错误处理模式更好: one try/catch around large block of code and many try/catches around smaller blocks of code?

转载 作者:行者123 更新时间:2023-12-03 08:20:51 24 4
gpt4 key购买 nike

这是关于风格的问题。这些模式中的哪一种是处理错误的更好方法?

模式1:

Try {
function1();
} catch (err) {
console.log(‘function1() threw the following error:’, err);
}

Try {
function2();
} catch (err) {
console.log(‘function2() threw the following error:’, err);
}

Try {
function3();
} catch (err) {
console.log(‘function3() threw the following error:’, err);
}

模式2:
Try {
function1();
function2();
function3();
} catch (err) {
console.log(‘The following error was thrown:’, err);
}

我发现模式1更具体,您可以准确记录错误发生的位置/原因(即“function1()引发错误……”)。是的,您可以依靠err中的错误消息,但这并不总是有用的(例如,“无法引用未定义的属性”不会告诉您来自哪个函数)。

另一方面,模式2简洁得多(即,更少的代码,更易于维护),但要付出专一性的代价。

是因为一种模式优于另一种模式还是仅出于个人喜好?

最佳答案

通常,我只是出于阅读说明的目的而打破了我的try/catching,类似于函数。两种方法的运行速度几乎相同,因此出于效率考虑,两者都是可以接受的。最好将错误具体化。我的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);
}

关于error-handling - 哪种错误处理模式更好: one try/catch around large block of code and many try/catches around smaller blocks of code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57258215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com