`
zccst
  • 浏览: 3292350 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

再次学习try catch finally

阅读更多
作者:zccst

一、基本介绍
JavaScript的错误
1、使用Mozilla浏览器的用户可以直接在Tools下的Javascript Console进行查看浏览器找到的错误.
2、自己使用例外处理来捕获JavaScript的异常。

如下是Javascript的例外处理的一个实例。
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");
}


运行结果:
Error name: TypeError
Error message: Cannot read property '0' of null

同时,还弹出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处理函数使用不当


三、除了基本的try...catch...finally,还可以配合throw精确的捕获异常
例如:

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>


function myFunction() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try { 
        x = Number(x);
        if(x == "") throw "is empty";
        if(isNaN(x)) throw "is not a number";
        if(x > 10) throw "is too high";
        if(x < 5) throw "is too low";
    }
    catch(err) {
        message.innerHTML = "Error: " + err + ".";
    }
    finally {
        document.getElementById("demo").value = "";
    }
}




完整版总结:
1,有try...catch...finally
2,可以有throw
3,可以有多个catch捕获不同的异常

try {
   try_statements
}
[catch (exception_var_1 if condition_1) { // non-standard
   catch_statements_1
}]
...
[catch (exception_var_2) {
   catch_statements_2
}]
[finally {
   finally_statements
}]
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics