Javascript错误处理与try .. catch ..最后 [英] Javascript error handling with try .. catch .. finally

查看:123
本文介绍了Javascript错误处理与try .. catch ..最后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怀疑我正在使用最终块,我不明白其目的的基本原理...

  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 returning true after your try block

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

这篇关于Javascript错误处理与try .. catch ..最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆