首页教程Javascript

异常

JavaScript 异常的抛出和处理


需要使用到以下四个语句

  • try 测试代码块的错误。
  • catch 处理错误。
  • throw 创建自定义错误。
  • finally 在 try 和 catch 语句之后,无论是否有触发异常,该语句都会执行。

throw

throw 语句允许我们创建自定义错误。

若 throw 与 try 和 catch 一起使用,就能够控制程序流,并生成自定义的错误消息。

//throw 语法 throw exception

exception可以是 JavaScript 字符串、数字、逻辑值或对象。


try 和 catch

try 和 catch 是成对出现的

语法

try { ... //异常会在这里抛出 } catch(e) { ... //捕获处理异常 } finally { ... //结束处理 }

假设我们再try内部有错误, 比如如下的函数名写错了

var txt=""; function message() { try { adddlert("is there any error?"); } catch(err) { txt = "Error!\n"; txt += "Description:" + err.message + "\n"; alert(txt); } }

finally 语句

finally 语句会不管 try 和 catch 有没有产生异常都会执行该代码块

function validateInput(value) { if (value === "") { throw "empty"; } if (isNaN(value)) { throw "not num"; } const x = Number(value); if (x > 10) { throw "too large"; } if (x < 5) { throw "too small"; } return x; } function myFunction() { var message = document.getElementById("p01"); var inputValue = document.getElementById("demo").value; try { var x = validateInput(inputValue); } catch (err) { message.innerHTML = "Error: " + err; } finally { document.getElementById("demo").value = ""; // 清空输入框 } }

关于try, catch, finally三者的执行顺序

我们直接以实例来阐明

function f() { try { console.log(0); throw 'bug'; } catch(e) { console.log(1); return true; // 这句原本会延迟到 finally 代码块结束再执行 console.log(2); // 不会运行 } finally { console.log(3); return false; // 这句会覆盖掉前面那句 return console.log(4); // 不会运行 } console.log(5); // 不会运行 } var result = f(); // 0 // 1 // 3 result // false

上面代码中,catch代码块结束执行之前,会先执行finally代码块。