17异常错误对象
# 异常错误对象
# 1、常见的错误类型
console.log(num); //这种就直接报错红色
//RangeError 已发生超出数字范围的错误
var num = 1;
try {
num.toPrecision(500); // 数无法拥有 500 个有效数
}
catch(err) {
}
//ReferenceError 已发生非法引用✨
var x;
try {
x = y + 1; // y 无法被引用(使用)
}
catch(err) {
}
//SyntaxError 已发生语法错误✨
try {
eval("alert('Hello)"); // 缺少 ' 会产生错误
}
catch(err) {
}
//TypeError 已发生类型错误✨
var num = 1;
try {
num.toUpperCase(); // 您无法将数字转换为大写
}
catch(err) {
}
//URIError 在 encodeURI() 中已发生的错误
try {
decodeURI("%%%"); // 您无法对这些百分号进行 URI 编码
}
catch(err) {
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 2、错误捕捉语句
//try 语句允许您定义一个代码块,以便在执行时检测错误
//catch 语句允许你定义一个要执行的代码块,如果 try 代码块中发生错误
//e是 Error 错误对象 name 错误的名字 message 错误的信息
try{
}catch(e){
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 3、抛出一个异常
//throw允许您创建自定义错误
throw
throw "Too big"; // 抛出文本
throw 500; //抛出数字
//案例
var a = 1;
try{
console.log(b);
}catch(e){
if(e.name === "ReferenceError"){
throw "你是不是没有定义该变量?"
throw new Error("是否没有定义变量")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 4、最终语句
//finally允许您在 try 和 catch 之后执行代码,无论结果
finally
//案例
var a = 1;
try{
console.log(b);
}catch(e){
console.log(e)
}
finally{
console.log("无论对错,都会执行这里的语句")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
编辑 (opens new window)
上次更新: 2022/04/24, 13:33:34