javaScrpt的保安——try/catch

try/catch

用法如下:

  1. 将要尝试执行的代码放在try块中
  2. catch块包含try块中代码出现错误时将执行的代码。

举个例子:

        window.onload = function(){
                try{
                        var message = document.getElementById("message");
                        message.innerHTML = "Hello world!";
                }catch(error){
                        alert(error.message);
                }
        };

在关键字catch后面的括号中的变量,只要try块中出现错误,就会捕获异常,并将一个与异常相关的值赋给这个变量。

谢谢阅读。

猜你喜欢

转载自blog.csdn.net/weixin_40763897/article/details/88105334