高程3总结#第17章错误处理与调试

错误处理与调试

错误处理

try-catch语句

try{
  //可能会导致错误的代码
}catch(error){
  //在错误发生时怎么处理
}
  • 发生错误时可以显示浏览器给出的信息

    try{
      window.someNonexistentFunction();
    }catch(error){
      alert(error.message);
    }
  • 在try-catch语句中是可选的,但finally子句一经使用,代码无论如何都会执行,try语句块中的代码全部正常执行,finally子句会执行,如果因为出错而执行了catch语句块,finally子句照样还会执行。只要代码中包含finally子句,无论try或catch语句块中包含什么代码,甚至return语句,都不会阻止finally子句的执行

    function testFinally(){
      try{
        return 2;
      }catch(error){
        return 1;
      }finally {
        return 0;
      }
    }
  • ECMA-262定义了7种错误类型

    • Error,是基类型,其他错误类型都继承自该类型
    • EvalError,错误会在使用eval()函数而发生异常时被抛出

      new eval();//抛出EvalError
      eval=foo;//抛出EvalError
    • RangeError,在数值超出相应范围时触发

      var items1=new Array(-20);//抛出RangeError
      var items2=new Array(Number.MAX_VALUE);//抛出RangeError
    • ReferenceError,找不到对象时,抛出这个错误

      var obj=x;//在x并未声明的情况下抛出ReferenceError
    • SyntaxError,把语法错误的JavaScript传入eval()函数时触发

      eval("a++b");//抛出SyntaxError
    • TypeError,在变量中保存着意外的类型,或者访问不存在的方式时触发

      var o=new 10;//抛出TypeError
      alert("name" in true);//抛出TypeError
      Function.prototype.toString.call("name");//抛出TypeError
    • URIError,使用encodeURI()或decodeURI()而URI格式不正确时触发

抛出错误

  • 与try-catch语句相配的还有一个throw操作符,用于随时抛出自定义错误。抛出错误时,必须要给throw操作符指定一个值,这个值是什么类型。没有要求

    throw 12345;
    throw "Hello world!";
    throw true;
    throw {name:"JavaScript"};
  • 也可以模拟出类似的浏览器错误

    throw new SyntaxError("I don’t like your syntax.");
    throw new TypeError("What type of variable do you take me for?");
    throw new RangeError("Sorry, you just don’t have the range.");
    throw new EvalError("That doesn’t evaluate.");
    throw new URIError("Uri, is that you?");
    throw new ReferenceError("You didn’t cite your references properly.");
  • 抛出错误的时机

    //函数会在参数不是数组的情况下失败
    function process(values){
      value.sort();
      for(var i=0,len=values.length;i<len;i++){
        if(value[i]>100){
          return values[i];
        }
      }
      return -1;
    }
    • 以上代码,不同浏览器给出不同错误信息

      • IE,属性或方法不存在
      • Firefox,values.sort()不是函数
      • Safari,值undefined
      • Chrome,对象名没有方法sort
      • Opera,类型不匹配
//函数重写
function process(values){
  if (!(values instanceof Array)){
    throw new Error("process(): Argument must be an array.");
  }
  values.sort();
  for (var i=0, len=values.length; i < len; i++){
    if (values[i] > 100){
      return values[i];
    }
  }
  return -1;
}
  • 重写后的函数中,如果values参数不是数组,就会抛出一个错误,错误消息中包含了函数的名称,以及为什么会发生错误的明确描述

错误(error)事件

  • 任何没有通过try-catch处理的错误都会触发window对象的error事件
  • 在任何Web浏览器中,onerror事件处理程序都不会创建event对象,但可以接收三个参数:错误消息,错误所在的URL和行号
  • 只要发生错误,无论是不是浏览器生成的,都会触发error事件,并执行这个事件处理程序
  • 在事件处理程序中返回false可以阻止浏览器报告错误的默认行为

    window.onerror=function(message,url,line){
      alert(message);
      return false;
    }

常见错误类型

  • 一般需要关注三种错误

    • 类型转换错误
    • 数据类型错误
    • 通信错误

区分致命错误和非致命错误

  • 非致命错误

    • 不影响用户的主要任务
    • 只影响页面的一部分
    • 可以恢复
    • 重复相同的操作可以消除错误
  • 致命错误

    • 应用程序根本无法继续运行
    • 错误明显影响到了用户的主要操作
    • 会导致其他连带错误

把错误记录到服务器

for(var i=0,len=mods.length;i<len;i++){
  try{
    mods[i].init();
  }catch(ex){
    logError("nonfatal","Module init failed:"+ex.message)
  }
}

调试技术

将消息记录到控制台

  • 可以通过console对象向JavaScript控制台中写入信息,这个对象具有下列方法

    • error(message),将错误信息记录到控制台
    • info(message),将信息性消息记录到控制台
    • log(message),将一般消息记录到控制台
    • warn(message),将警告消息记录到控制台
    function sum(num1, num2){
      console.log("Entering sum(), arguments are " + num1 + "," + num2);
      console.log("Before calculation");
      var result = num1 + num2;
      console.log("After calculation");
      console.log("Exiting sum()");
      return result;
    }

将消息记录到当前页面

  • 在页面 中开辟一小块区域,用以显示信息,这个区域通常是一个元素,而该元素可以总是出现在页面中,但仅用于调试目的,也可以是一个根据需要动态创建的元素

    function log(message){
      var console = document.getElementById("debuginfo");
      if (console === null){
        console = document.createElement("div");
        console.id = "debuginfo";
        console.style.background = "#dedede";
        console.style.border = "1px solid silver";
        console.style.padding = "5px";
        console.style.width = "400px";
        console.style.position = "absolute";
        console.style.right = "0px";
        console.style.top = "0px";
        document.body.appendChild(console);
      }
      console.innerHTML += "<p>" + message + "</p>";
    }

抛出错误

  • 可以使用assert()函数代替某些函数中需要调试的if语句,以便输出错误消息

    function assert(condition, message){
      if (!condition){
        throw new Error(message);
      }
    }
    function divide(num1, num2){
      assert(typeof num1 == "number" && typeof num2 == "number",
             "divide(): Both arguments must be numbers.");
      return num1 / num2;
    }

评论

暂无评论