Throw、Try 、Catch

总体概括

try 语句测试代码块的错误。

catch 语句处理错误。

throw 语句创建自定义错误。


try跟catch之间的联系

try 语句允许我们定义在执行时进行错误测试的代码块(测试)。

catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块(捕捉)。

trycatch 成对出现

语法

try
  {
      //可能会导致错误的代码
  }
catch(err)
  {
      //在错误发生时怎么处理
  }

实例

<!DOCTYPE html>
<html>
<head>
  <script>
    var txt="";
    function message() {
      try {
        adddlert("Welcome guest!");
      } catch(err) {
        txt="There was an error on this page.\n\n";
        txt+="Error description: " + err.message + "\n\n";
        txt+="Click OK to continue.\n\n";
        alert(txt);
      }
    }
  </script>
</head>

<body>
<input type="button" value="View message" onclick="message()">
</body>

</html>

如上例:alert 拼写错误 adddlert

err的内容为ReferenceError: adddlert is not defined

catch 捕捉到错误之后执行下半部分代码

∴弹出框的内容为There was an error on this page.Error description: adddlert is not defined Click OK to continue.


finally 子句

语法 + 实例

try {
    return 2;
} catch (error) {
    return 1;
} finally {
    return 0;
}

如上例:若使用finally子句,就会导致try与catch语句中的return被忽略,最终只返回0


Throw 语句

throw 语句允许我们创建自定义错误(创建或抛出异常)。

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

语法

throw _exception_

异常可以是 JavaScript 字符串、数字、逻辑值或对象

实例

<script>
function myFunction()
{
try
  {
  var x=document.getElementBytId("demo").value;
  if(x=="")    throw "empty";
  if(isNaN(x)) throw "not a number";
  if(x>10)     throw "too high";
  if(x<5)      throw "too low";
  }
catch(err)
  {
  var y=document.getElementById("mess");
  y.innerHTML="Error: " + err + ".";
  }
}
</script>

<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>

如上例: 当input的输入内容符合if条件,则显示相应的err

js基础教程——Throw、Try 、Catch

遗漏点补充
JSRUN前端笔记, 是针对前端工程师开放的一个笔记分享平台,是前端工程师记录重点、分享经验的一个笔记本。JSRUN前端采用的 MarkDown 语法 (极客专用语法), 这里属于IT工程师。