异常处理语句

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

  • throw 语句
  • try…catch 语句

异常类型

点击查看MDN文档


throw 语句

使用 throw 语句抛出一个异常。当你抛出异常,你规定一个含有值的表达式要被抛出。

1
throw expression;

例如:

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

⚠️注意:你可以在抛出异常时声明一个对象。那你就可以在catch块中查询到对象的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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 语句就捕获它。

try...catch 语句有一个包含一条或者多条语句的 try 代码块,0个或多个的 catch 代码块,catch 代码块中的语句会在 try 代码块中抛出异常时执行。

如果 try 代码块中的语句(或者 try 代码块中调用的方法)一旦抛出了异常,那么执行流程会立即进入 catch 代码块。如果 try 代码块没有抛出异常,catch 代码块就会被跳过。
例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function getMonthName(mo) {
mo = mo - 1; // 根据 months 数组的索引调整月份数 (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"; // 抛出异常
}
}

try { // 声明 try
monthName = getMonthName(myMonth); // 如果执行中抛出异常
}
catch (e) {
monthName = "unknown";
logMyErrors(e); // 执行自己的异常处理事件
}

catch

你可以使用 catch 块来处理所有可能在 try 块中产生的异常。

1
2
3
catch (catchID) {
statements
}

捕捉块指定了一个标识符(上述语句中的 catchID )来存放抛出语句指定的值;你可以用这个标识符来获取抛出的异常信息。在插入 throw 块时 JavaScript 创建这个标识符;标识符只存在于 catch 块的存续期间里;当 catch 块执行完成时,标识符不再可用。

1
2
3
4
5
6
try {
throw "myException" // 抛出异常
}
catch (e) {
logMyErrors(e) // 捕获异常 处理异常
}

finally

⚠️注意:无论是否抛出异常finally子句都会执行。但重点不是finally子句总是会执行,而是try..catch语句后面的其它普通代码不会执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
try {
throw new Error("oops");
}
catch (ex) {
console.error("inner", ex.message);
}
finally {
console.log("finally");
}

// Output:
// "inner" "oops"
// "finally"

嵌套 try...catch 语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
try {
throw new Error("oops");
}
catch (ex) {
console.error("inner", ex.message);
}
finally {
console.log("finally");
}
}
catch (ex) {
console.error("outer", ex.message);
}

// Output:
// "inner" "oops"
// "finally"

使用 Error 对象

namemessage 获取更精炼的信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)
}