js捕捉函数中的错误(利用try。。。catch)

利用try。。catch函数来捕捉自己编写的函数的错误,并把错误显示在网页上:

1、首先编写一个函数(需要抛出【throw】错误的类型以及报错信息):

js捕捉函数中的错误(利用try。。。catch)

2、用try。。。catch在执行函数的过程中捕捉错误:

js捕捉函数中的错误(利用try。。。catch)

直接运行:得到以下结果:

js捕捉函数中的错误(利用try。。。catch)

即可完成对函数错误的捕捉:

源代码如下:

$(function(){
    try{
        test('123');
    }catch(e){
        document.writeln(e.name+":"+e.message)
    }
});
function test(a){
    if(typeof a !='number'){
        throw{
            name:'typeError',
            message:'a 的类型需要必须为number类型'
        };
    }
    return a;
}