教程集 www.jiaochengji.com
教程集 >  脚本编程  >  javascript  >  正文 再次学习try catch finally

再次学习try catch finally

发布时间:2016-09-05   编辑:jiaochengji.com
教程集为您提供再次学习try catch finally等资源,欢迎您收藏本站,我们将为您提供最新的再次学习try catch finally资源

一、基本介绍

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
}]

您可能感兴趣的文章:
再次学习try catch finally
Python finally-资源回收
asp.net实现备份与恢复Sql Server数据库
java多线程例子学习笔记
java中try-catch-finally异常处理例子
ASP.NET中备份SQL Server数据库的方法
JAVA中的异常与错误处理详解
Java读取文件例子代码
c# 开机启动项实例代码
Java入门笔记5_异常

[关闭]
~ ~