JavaScript进阶09笔记
异常处理语句
你可以用 throw
语句抛出一个异常并且用 try...catch
语句捕获处理它。
-
throw
语句 -
try...catch
语句
异常类型
JavaScript 可以抛出任意对象。然而,不是所有对象能产生相同的结果。尽管抛出数值或者字母串作为错误信息十分常见,但是通常用下列其中一种异常类型来创建目标更为高效:
-
ECMAScript exceptions
-
DOMException
andDOMError
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
流程的返回值,不管在try
和catch
块中语句返回了什么:
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();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具