try
每个try块必须与至少一个catch或finally块,否则会抛出SyntaxError错误。
单独使用try块进行验证:
try {
throw new Error('Error while executing the code');
}
1
2
3
ⓧ Uncaught SyntaxError: Missing catch or finally after try
1
try…catch
将try与catch块一起使用,可以处理try块抛出的错误。
try {
throw new Error('Error while executing the code');
} catch (err) {
console.error(err.message);
}
ⓧ Error while executing the code
try…catch 与 无效代码
try…catch 无法捕获无效的 JS 代码,例如try块中的以下代码在语法上是错误的,但它不会被catch块捕获。
try {
~!$%^&*
} catch(err) {
console.log("这里不会被执行");
}
ⓧ Uncaught SyntaxError: Invalid or unexpected token
1
try…catch 与 异步代码
try…catch无法捕获在异步代码中引发的异常,例如setTimeout:
try {
setTimeout(function() {
noSuchVariable; // undefined variable
}, 1000);
} catch (err) {
console.log("这里不会被执行");
}
未捕获的ReferenceError将在1秒后引发:
ⓧ Uncaught ReferenceError: noSuchVariable is not defined
应该在异步代码内部使用 try…catch 来处理错误:
setTimeout(function() {
try {
noSuchVariable;
} catch(err) {
console.log("error is caught here!");
}
}, 1000);
嵌套 try…catch
使用嵌套的try和catch块向上抛出错误
try {
try {
throw new Error('Error while executing the inner code');
} catch (err) {
throw err;
}
} catch (err) {
console.log("Error caught by outer block:");
console.error(err.message);
}
Error caught by outer block:
ⓧ Error while executing the code
1
2
try…finally
仅使用 try…finally 而没有 catch 块
try {
throw new Error('Error while executing the code');
} finally {
console.log('finally');
}
finally
ⓧ Uncaught Error: Error while executing the code
注意
即使从try块抛出错误后,也会执行finally块
如果没有catch块,错误将不能被优雅地处理,从而导致未捕获的错误
try…catch…finally
使用try…catch块和可选的finally块
try {
console.log("Start of try block");
throw new Error('Error while executing the code');
console.log("End of try block -- never reached");
} catch (err) {
console.error(err.message);
} finally {
console.log('Finally block always run');
}
console.log("Code execution outside try-catch-finally block continue..");
Start of try block
ⓧ Error while executing the code
Finally block always run
Code execution outside try-catch-finally block continue..
注意
在try块中抛出错误后往后的代码不会被执行了
即使在try块抛出错误之后,finally块仍然执行
finally块通常用于清理资源或关闭流
try {
openFile(file);
readFile(file);
} catch (err) {
console.error(err.message);
} finally {
closeFile(file);
}
throw
throw语句用于引发异常
// throw primitives and functions
throw "Error404";
throw 42;
throw true;
throw {toString: function() { return "I'm an object!"; } };
// throw error object
throw new Error('Error while executing the code');
throw new SyntaxError('Something is wrong with the syntax');
throw new ReferenceError('Oops..Wrong reference');
// throw custom error object
function ValidationError(message) {
this.message = message;
this.name = 'ValidationError';
}
throw new ValidationError('Value too high');