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>