JS中的try...catch
try...catch
try...catch语句标记要尝试的语句块,并指定一个出现异常时抛出的响应。
语法
try {
// 需要被执行的语句。
// try_statements
}
// 如果在try块里有异常被抛出时执行的语句。
catch (exception) {
// catch_statements
}
// 在try语句块之后执行的语句块。无论是否有异常抛出或捕获这些语句都将执行。
finally {
// finally_statements
}
描述
try语句包含了由一个或者多个语句组成的try块, 和至少一个catch块或者一个finally块的其中一个,或者两个兼有, 下面是三种形式的try声明:
- try...catch;
- try...catch...finally;
- try...finally;
catch子句包含try块中抛出异常时要执行的语句。也就是,你想让try语句中的内容成功, 如果没成功,你想控制接下来发生的事情,这时你可以在catch语句中实现。 如果在try块中有任何一个语句(或者从try块中调用的函数)抛出异常,控制立即转向catch子句。如果在try块中没有异常抛出,会跳过catch子句。
finally子句在try块和catch块之后执行但是在下一个try声明之前执行。无论是否有异常抛出或捕获它总是执行。
你可以嵌套一个或者更多的try语句。如果内部的try语句没有catch子句,那么将会进入包裹它的try语句的catch子句。
条件catch块
你也可以用一个或者更多条件catch子句来处理特定的异常。在这种情况下,当异常抛出时将会进入合适的catch子句中。在下面的代码中,try块的代码可能会抛出三种异常:TypeError,RangeError和EvalError。当一个异常抛出时,控制将会进入与其对应的catch语句。如果这个异常不是特定的,那么控制将转移到无条件catch子句。
当用一个无条件catch子句和一个或多个条件语句时,无条件catch子句必须放在最后。否则当到达条件语句之前所有的异常将会被非条件语句拦截。
不符合ECMAscript 规范的示例
try {
myroutine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
// statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
// statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
// statements to handle EvalError exceptions
} catch (e) {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
符合ECMAscript 规范的示例
try {
myroutine();
} catch (e) {
// statements to handle this very common expected error
if (e instanceof TypeError) {
// statements to handle this very common expected error
} else {
throw e; // re-throw the error unchanged
}
}
嵌套 try 块
示例 1
try {
try {
// throw 语句抛出一个错误 错误发生时JavaScript会停止并抛出错误信息
throw new Error('oops');
}
finally {
console.log('finally');
}
}
catch (e) {
console.error('outer', e.message);
}
// Output:
// 'finally'
// 'outer' 'oops'
示例 2
try {
try {
throw new Error('oops');
}
catch (e) {
console.error('inner', e.message);
throw e;
}
finally {
console.log('finally');
}
}
catch (e) {
console.error('outer', e.message);
}
// Output:
// 'inner' 'oops'
// 'finally'
// 'outer' 'oops'
// 任何给定的异常只会被离它最近的封闭 catch 块捕获一次。当然,在“inner”块抛出的任何新异常 (因为 catch 块里的代码也可以抛出异常),将会被“outer”块所捕获。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通