JavaScript进阶09笔记

错误处理

异常处理语句

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

  • throw语句

  • try...catch语句

异常类型

JavaScript 可以抛出任意对象。然而,不是所有对象能产生相同的结果。尽管抛出数值或者字母串作为错误信息十分常见,但是通常用下列其中一种异常类型来创建目标更为高效:

  • ECMAScript exceptions

  • DOMException and DOMError

 

throw 语句

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

throw expression;

你可以抛出任意表达式而不是特定一种类型的表达式。下面的代码抛出了几个不同类型的表达式:

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

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

// 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 代码块中的代码如果没有执行成功,那么你希望将执行流程转入 catch 代码块。

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

  • 如果 try 代码块没有抛出异常,catch 代码块就会被跳过。

finally 代码块总会紧跟在 try 和 catch 代码块之后执行,但会在 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

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

catch (catchID) {
 statements
}

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

 

举个例子,下面代码抛出了一个异常。当异常出现时跳到catch块。

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

 

finally

finally块包含了在 try 和 catch 块完成后、下面接着 try...catch 的语句之前执行的语句。finally块无论是否抛出异常都会执行。如果抛出了一个异常,就算没有异常处理,finally块里的语句也会执行。

你可以用finally块来令你的脚本在异常发生时优雅地退出;举个例子,你可能需要在绑定的脚本中释放资源。接下来的例子用文件处理语句打开了一个文件(服务端的 JavaScript 允许你进入文件)。如果在文件打开时一个异常抛出,finally块会在脚本错误之前关闭文件。

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
}

如果finally块返回一个值,该值会是整个try-catch-finally流程的返回值,不管在trycatch块中语句返回了什么:

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

finally块覆盖返回值也适用于在catch块内抛出或重新抛出的异常

function f() {
try {
throw 'bogus';
} catch(e) {
console.log('caught inner "bogus"');
throw e; // this throw statement is suspended until
// finally block has completed
} finally {
return false; // overwrites the previous "throw"
}
// "return false" is executed now
}

try {
f();
} catch(e) {
// this is never reached because the throw inside
// the catch is overwritten
// by the return in finally
console.log('caught outer "bogus"');
}

// OUTPUT
// caught inner "bogus"

 

Error对象

根据错误类型,你也许可以用'name'和'message'获取更精炼的信息。'name'提供了常规的错误类(如 'DOMException' 或 'Error'),而'message'通常提供了一条从错误对象转换成字符串的简明信息。

 

在抛出你个人所为的异常时,为了充分利用那些属性(比如你的catch块不能分辨是你个人所为的异常还是系统的异常时),你可以使用 Error 构造函数。比如:

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)
}

posted on   u_Dawn  阅读(4)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示