【JS基础】try catch 用法

try catch 用法

try…catch 语句是什么?

try…catch 可以测试代码中的错误。try 部分包含需要运行的代码,而 catch 部分包含错误发生时运行的代码

try…catch语法
try {
    // 在此运行代码
} catch(err) {
    // 在此处理错误
}

运行流程:
try{...}包含块中的代码有错误,则运行catch(err){...}内的代码,否则不运行catch(err){...}内的代码
try…catch案例
var array = null;
try {
    document.write(array[0])
} catch(err) {
    document.writeln('error name' + err.name + '');
    document.writeln('error message: ' + err.message);
}

在这里插入图片描述

try…catch…finally语法
try {
    tryStatements
} catch(exception) {
    catchStatements
} finally {
    finallyStatements
}

参数
   tryStatements: 必选项,可能发生错误的语句
   exception: 必选项,任何变量名 exception 的初始化值是扔出的错误的值
   catchStatements 可选项,处理在相关联的 tryStatement 中发生的错误的语句
   finallyStatements: 可选项,在所有其他过程发生之后无条件执行的语句
try…catch…finally 案例
var array = null;
try {
    document.write(array[0])
} catch(err) {
    document.writeln('error name: ' + err.name + '' )
    document.writeln('error message: ' + err.message)
}
finally{
    alert('object is null');
}

程序执行过程
    1.array[0]的时候由于没有创建array数组,array是个空对象,程序中调用array[0]就会产生object is null 的异常
    2.catch(err)语句捕获到这个异常通过err.name打印了错误类型,err.message打印了错误的详细信息
    3.finally类似与java的finally,无论有无异常都会执行

现总结Error.name的六种值对应的信息:

  1. EvalError:eval()的使用与定义不一致
  2. RangeError:数值越界
  3. ReferenceError:非法或不能识别的引用数值
  4. SyntaxError:发生语法解析错误
  5. TypeError:操作数类型错误
  6. URIError:URI处理函数使用不当
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值