JavaScript的异常处理

in Notes with 0 comment

异常处理

用throw 语句抛出一个异常并且用try...catch 语句捕获处理它

异常类型

JavaScript可以抛出任意对象。但是通常用下列其中一种异常类型来创建目标更为高效

抛出语句

throw expression;

下面的代码抛出了几个不同类型的表达式

throw "Error2";   // String type
throw 42;         // Number type
throw true;       // Boolean type
throw {toString: function() { return "I'm an object!"; } };

你可以在抛出异常时声明一个对象。那你就可以在捕捉块中查询到对象的属性。下面的例子创建了一个UserException类型的对象myUserException用在抛出语句中。

// Create an object type UserException
function UserException (message){
  this.message=message;
  this.name="UserException";
}
// Make the exception convert to a pretty string when used as
// a string (e.g. by the error console)
UserException.prototype.toString = function (){
  return this.name + ': "' + this.message + '"';
}
// Create an instance of the object type and throw it
throw new UserException("Value too high");

try...catch 语句

下面的例子使用try...catch语句,其中的一个函数用于从一个数组中根据传递值来获取一个月份名称。如果该值与月份数值不相符,会抛出一个带有"InvalidMonthNo"值的异常,然后在捕捉块语句中设monthName变量为unknown

function getMonthName(mo) {
  mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
  var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul",
                "Aug","Sep","Oct","Nov","Dec"];
  if (months[mo]) {
    return months[mo];
  } else {
    throw "InvalidMonthNo"; //throw keyword is used here
  }
}
try { // statements to try
  monthName = getMonthName(myMonth); // function could throw exception
}
catch (e) {
  monthName = "unknown";
  logMyErrors(e); // pass exception object to error handler -> your own function
}

捕捉块

catch (catchID) {
  statements
}

捕捉块指定了一个标识符 (上述语句中的catchID)来存放抛出语句指定的值;你可以用这个标识符来获取抛出的异常信息

当异常出现时跳到捕捉块

try {
   throw "myException" // generates an exception
}
catch (e) {
// statements to handle any exceptions
   logMyErrors(e) // pass exception object to error handler
}

终结块

用终结块来令你的脚本在异常发生时优雅地退出

openMyFile();
try {
    writeMyFile(theData); //This may throw a error
}catch(e){
    handleError(e); // If we got a error we handle it
}finally {
    closeMyFile(); // always close the resource
}

如果终结块返回一个值,该值会是整个try-catch-finally流程的返回值

function f() {
  try {
    console.log(0);
    throw "bogus";
  } catch(e) {
    console.log(1);
    return true; // this return statement is suspended
                 // until finally block has completed
    console.log(2); // not reachable
  } finally {
    console.log(3);
    return false; // overwrites the previous "return"
    console.log(4); // not reachable
  }
  // "return false" is executed now  
  console.log(5); // not reachable
}
f(); // console 0, 1, 3; returns false

错误匹配对象

'name'提供了常规的错误类(e.g., 'DOMException' or 'Error')

'message'通常提供了一条从错误对象转换成字符串的简明信息

function doSomethingErrorProne () {
  if (ourCodeMakesAMistake()) {
    throw (new Error('The message'));
  } else {
    doSomethingToGetAJavascriptError();
  }
}
....
try {
  doSomethingErrorProne();
}
catch (e) {
  console.log(e.name); // logs 'Error'
  console.log(e.message); // logs 'The message' or a JavaScript error message)
}

阅读资料:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide

复习方式:实践(代码写一次、跑一次、测试一次),不懂的地方谷歌,阅读和做笔记

底线原则:宁可重写一次,也不复制粘贴

本次复习内容有:异常处理

复习耗时:大概2小时···我也不知道为什么这么久···

Responses