gpt4 book ai didi

使用 try .. catch .. finally 处理 Javascript 错误

转载 作者:IT王子 更新时间:2023-10-29 02:57:16 26 4
gpt4 key购买 nike

我怀疑我错误地使用了 finally block ,而且我不理解其目的的基本原理...

 function myFunc() {
try {
if (true) {
throw "An error";
}
} catch (e) {
alert (e);
return false;
} finally {
return true;
}
}

此函数将运行 catch block ,发出“错误”警报,但随后返回 true。为什么不返回 false?

最佳答案

The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception. more

finally block 将始终运行,尝试在 try block 之后返回 true

function myFunc() {
try {
if (true) {
throw "An error";
}
return true;
} catch (e) {
alert (e);
return false;
} finally {
//do cleanup, etc here
}
}

关于使用 try .. catch .. finally 处理 Javascript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/286297/

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