1.正常的异常处理
ps:finally是一定会被执行的。
2.自定义抛出错误
参考代码(上述1和2):
<!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>js异常处理</title>
</head>
<body>
<script>
// 1.异常处理流程
try {
console.log(1); // 1
var t = new jsf(); // 出异常语句,此处jsf未定义
console.log(2); // 未执行
} catch (e) {
console.dir(e) // ReferenceError: "jsf is not defined"
// <anonymous> file:///C:/Users/lisa/Documents/My/Learn_CodeTych/Vscode/JavaScript/learn_16_exeception.html:13
console.log(e.message); // jsf is not defined
} finally{
console.log("finally"); // finally (一定会被执行)
}
// alert('2333');
console.log(3); // 3
// 2.抛出异常
function add(a, b){
if(typeof(a) != "number"){
throw "传入参数不是整数类型"; // 只要遇到throw,程序就停止,代码立即跳转到catch语句,如果没有catch语句,当前js程序就会结束。
}
return a + b;
}
// var res = add('ad', 44); // 报错:uncaught exception: 传入参数不是整数类型
// console.log(2.1) // 未执行
try {
var res2 = add("asd", 2); // 将代码放在try catch中。
} catch (e) {
// 打印错误信息
console.log(e); // 传入参数不是整数类型 (由于是自己定义的,故这里直接用e,因为系统抛出的异常里,message里存的是异常信息,故捕获系统抛出的异常要用e.message)
}
console.log(2.2) // 2.2
</script>
</body>
</html>
3.错误信息对象Error
ps:catch中可以根据错误类型不同,做相关处理,不过浏览器不同兼容不好。
(略)