Article directory
1 description
We can place any code that may cause an exception in the try statement block, and define the method of handling the exception in the catch statement block.
If the code try 语句块
in 发生错误
, the code will immediately jump from the try statement block to the catch statement block.
If the code is in try
the statement block 没有发生错误
, the code in the catch statement block will be ignored.
If finally
the statement block exists, then 无论结果如何
finally will be executed.
2 Grammar
try {
... // 可能会发生异常的代码。
} catch (error) {
... // 发生异常时要执行的操作。
} finally {
... // 任何情况下都会执行。
}
3 instances
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>JavaScript</title>
</head>
<body>
<script>
try {
// 调用一个未定义的变量
document.write(str);
// 若发生错误,则不会执行以下行
alert("所有语句都已成功执行。");
} catch (error) {
// 处理错误
alert("错误信息: " + error.message);
} finally {
// 继续执行下面的代码
document.write("<p>Hello try catch!</p>");
}
</script>
</body>
</html>
NOTE: Both catch and finally statements are optional, but at least one must be used when using the try statement.