Javascript错误处理与try .. catch ..最后 [英] Javascript error handling with try .. catch .. finally
问题描述
我怀疑我正在使用最终
块,我不明白其目的的基本原理...
function myFunc(){
try {
if(true){
throw一个错误;
}
} catch(e){
alert(e);
返回false;
} finally {
return true;
}
}
此函数将运行抓住
阻止,提醒一个错误,但是返回true。为什么不返回false?
finally块包含在尝试后执行的语句并且catch块执行,但在try ... catch语句之后的语句之前。 finally块执行是否抛出异常。如果抛出异常,即使没有catch块处理异常,finally块中的语句仍然执行。
$ b
finally
块将始终运行,尝试在您的<$ c之后返回true
$ c> try 块function myFunc(){
try {
if(true){
throwAn error;
}
返回true;
} catch(e){
alert(e);
返回false;
} finally {
// do cleanup,etc here
}
}
I have a suspicion that I'm using the
finally
block incorrectly, and that I don't understand the fundamentals of its purpose...function myFunc() { try { if (true) { throw "An error"; } } catch (e) { alert (e); return false; } finally { return true; } }
This function will run the
catch
block, alert "An error", but then return true. Why doesn't it return 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
The
finally
block will always run, try returningtrue
after yourtry
blockfunction myFunc() { try { if (true) { throw "An error"; } return true; } catch (e) { alert (e); return false; } finally { //do cleanup, etc here } }
这篇关于Javascript错误处理与try .. catch ..最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!