天天看点

try 和 catch 用法try 和 catch 用法

try 和 catch 用法

参考文档

  • MDN | try…catch

作用:

  • 使用 try-catch 来将可能出现错误的代码进行包裹。
  • try 用来包裹可能出现错误的代码;如果 try 中的代码出错,就会马上执行 catch 中的代码,执行之后,后续的代码继续执行。

用法:

例🌰子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
</body>

<script>
    try {
        var a = 1
        var b = 2
        throw new Error()
    } catch(error) {
        console.log('出错啦')
    }
    console.log(a + b)
	// 输出: '出错啦'  3
</script>

</html>
           

继续阅读