The function of try...catch is to catch errors, regardless of system errors or custom errors (throw)
try…catch-JavaScript | MDN
try…catch statement marks the block of statements to be tried and specifies a response that is thrown when an exception occurs
try…catch[…finally] is used as follows
try {
// 被执行的语句
// 被执行的语句中触发了报错
throw "报错信息"
} catch(error) {
// error 返回的报错信息
// 如果在try块里有异常被抛出时执行的语句
// 没有错误则不会执行
console.log(error)
} finally {
// 在try语句块之后执行的语句块。无论是否有异常抛出或捕获这些语句都将执行
console.log("finally")
}
try…catch[…finally] can be a nesting doll (one layer of try…catch, one layer of try…catch, one layer of try…catch), the nearest catch will be found if an error is reported
If a value is returned from the finally block, then this value will become the return value of the entire try-catch-finally, regardless of whether there is a return statement in the try and catch. This includes exceptions thrown in the catch block.
For example, the entire try is in a function, and the return information of the finally can be used as the return information of the function.
function fun() {
try {
throw "报错信息"
} catch(error) {
console.log(error)
} finally {
return "finally.return 相当于上一级的 return"
}
console.log("finally.return 后的代码不执行")
}
console.log(fun())
// 报错信息
// finally.return 相当于上一级的 return
A complete error prompt has at least three steps
- Error: Create an error object
- throw: throw (trigger) an error
- try...catch: catch (handle) errors
General usage demonstration
function fun() {
// new Error() 创建一个错误对象
// 用 throw 抛出一个错误
throw new ReferenceError("这是一个报错信息")
}
try {
// 在 try 中执行一个可以报错的函数
fun()
} catch(error) {
// 函数如期抛出错误, 并被 catch 捕获
// 打印捕获的报错信息
console.log(error)
}
Error prompt three consecutive
- js Error Essays-Error Tips Sanlian's Error
- js throw statement essay-error report and three consecutive throw
- js try...catch statement essay-error prompts three consecutive try...catch
end