文章分类 | 推荐文章 | 最新文章 | 热点文章 | 最新软件 | 精品软件 | 下载排行 | 推荐下载 | WPS | 杀毒软件
清风网络
首 页 软件下载 网络学院
QQ 电脑入门 游戏 操作系统 图形处理 办公软件 媒体动画 精文荟萃 工具软件 网络编程 程序开发 网络技术 认证考试 网站建设 文章专栏
当前位置:清风网络网络编程Script谨慎处理JavaScript中的错误
精品推荐
特别推荐
·主页javascript特效19则
·各种网页媒体播放器代码及详解
·用户体验:JS实现仿新浪信息提示效果
·网页特效:图片随机显示实例详解
·JavaScript入门学习书籍的阶段选择
·Javascript代码轻松隐藏网页源文件
·网页制作:JavaScript仿Windows关机效果
·网页制作Javascript经典小技巧总结
热点TOP10
·javascript实现语法分色编辑器
·JavaScript经典效果集锦(二)
·总结性知识:107个常用Javascript语句
·Javascript模拟的DOS窗口代码实例
·用vbscript实现在文本文件中搜索两个项
·JavaScript应用实例:网页折叠菜单
·撕页广告代码及简介
·用javascript作消息提示框(类似于QQ用户上线的消息提示)

谨慎处理JavaScript中的错误

日期:2007年5月16日 作者: 查看:[大字体 中字体 小字体]

不管你的技术水平如何,错误或异常是应用程序开发者生活的一部分。Web开发的不连贯性留下了许多错误能够发生并确实已经发生的地方。解决的关键在于处理任何不可预见的(或可预见的错误),来控制用户的体验。利用JavaScript,就有多种技术和语言特色可以用来正确地解决任何问题。

事事检查

在开始之前检查一切是一个好的编程习惯,也就是说,你应该在利用它们之前,检查对象、方法调用等的有效性。这样就避免了与未实例化对象或对不存在的方法调用有关的错误。列表A在使用对象(变量和字段)之前会对它们进行检查。在使用字段对象之前,该脚本保证它们为有效或非空字段。

列表A

以下为引用的内容:

<html>
<head>
<title>JS Test</title>
<script type="text/javascript">
function validate() {
var doc = document.forms[0];
var flag = true;
if (doc != null) {
if (doc.fullName != null) {
if (doc.fullName.value == '') {
flag = false;
}
} else      {
flag = false;
}
if (doc.contactNumber != null) {
if (doc.contactNumber.value == '') {
flag = false;
}
} else {
flag = false;
}
if (flag) {
alert('Validation successful, document will be submitted.');
doc.submit();
} else {
alert('Enter values before submitting.');
} }
return 0; }
</script>
</head>
<body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="validate();">
</form>
</body>
</html>

你并不需要实际地检查有效性——你可以简单地在if 语句中使用一个对象,如果它不是一个无效对象的话,所求得的值就为真。列表B就用了这种句法,同时也用到了getElementByID方法。它用了一个if语句来保证在继续之前getElementByID方法是被支持的(存在)。

列表B

以下为引用的内容:

<html><head>
<title>JS Test</title>
<script type="text/javascript">
function validate() {
var doc = document.forms[0];
var flag = true;
if (doc != null) {
if (doc.getElementById) {
if (doc.getElementById("fullName")) {
if (doc.fullName.value == '') {
flag = false;
}
} else {
flag = false;
}
if (doc.getElementById("contactNumber")) {
if (doc.contactNumber.value == '') {
flag = false;
}
} else {
flag = false;
}
if (flag) {
alert('Validation successful, document will be submitted.');
doc.submit()
} else {
alert('Enter values before submitting.');
} }
return 0; }
</script>
</head>
<body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="validate();">
</form>
</body>
</html>

虽然在使用对象之前检查它们是一个好方法,但是有时候还是会有错误出现。在这些实例中,JavaScript语言使得发现错误变得简单,从而能够继续下去。

发现错误

和Java、C#等其他语言相类似,JavaScript中包括了try/catch/finally语句。一个try语句包含了一组代码,在这组代码中,像运行时间错误这样的异常可能会发生。catch子句概述了怎样处理错误,finally块中包括了始终被执行的代码。

一般来说,代码设法执行一组代码,如果没有执行成功的话,支配权就传到catch块。如果没有错误发生,就跳过catch块。finally块在try和catch块完毕后执行。它的句法如下:

以下为引用的内容:
try
{
// code
}
catch
{
// code
}
finally
{
// code
}

catch和finally块是可选的,但是如果没有catch块是没有意义的。仔细考虑列表C,它示范了try/catch/finally的用法。从被引用的字段在表格中不存在开始,错误就发生了。

列表C

以下为引用的内容:

<html>
<head>
<title>JS Test</title>
<script type="text/javascript">
function doIt() {
if (document.forms[0].firstName.value == '') {
// do something
}
return 0; }
</script>
</head>
<body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form>
</body>
</html>

一个try/catch块不能避免错误,但是它能够很得体地处理错误,这样用户就不会面对晦涩的浏览器出错信息。观察列表D。

列表D

以下为引用的内容:

<html>
<head>
<title>JS Test</title>
<script type="text/javascript">
function doIt() {
try {
if (document.forms[0].firstName.value == '') {
// do something
}
} catch(e) {
document.write("An unexpected error has occurred.<br><br>");
document.write("Please contact the administrator.<br><br>");
document.write(e.message);
} finally {
document.forms[0].submit();
}
return 0; }
</script></head>
<body>


<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

它提示了以下信息,但是finally块保证了窗体的提交——不管有什么错误发生。

以下为引用的内容:
An unexpected error has occurred.
Please contact the administrator.
'document.forms.0.firstName.value' is null or not an object

单个catch块可以处理所有问题,但是多个catch语句可以被用来处理特定的错误。这个问题在下个部分会涉及到。

用try/catch语句可以很容易地处理不可预见的错误。在某些情况下,可能你想以不同的方式处理错误,JavaScript提供了throw语句。它的句法是很基本的——throw后面紧跟要发生的异常。这就使得你能够定义和引发自定义的异常。列表E中的代码创建了一个缺失值的异常,并且它是生成的。

列表E

以下为引用的内容:
<html><head>
<title>JS Test</title>
<script type="text/javascript">
function MissingValueException (errMsg) {
this.message = errMsg;
this.name="MissingValueException";
}
function doIt() {
try {
if (document.forms[0].fullName.value == '') {
noNameException = new MissingValueException("First name is missing.");
throw noNameException;
} else {
document.forms[0].submit();
}
} catch(e) {
document.write("An unexpected error has occurred.<br>");
document.write("Please contact the administrator.<br>");
document.write(e.message);
} finally {
document.forms[0].submit();
}
return 0; }
</script></head><body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

它将会显示以下信息(如果在字段中没有值输入的话):

以下为引用的内容:

An unexpected error has occurred.
Please contact the administrator.
First name is missing.

除此之外,你还可以用运算符instanceof来确定异常的类型,从而做出反应。列表F中的代码会检查异常对象的类型并相应地显示有关数据。

列表F

以下为引用的内容:

<html>
<head>
<title>JS Test</title>
<script type="text/javascript">
function MissingValueException (errMsg) {
this.message = errMsg;
this.name="MissingValueException";
}
function doIt() {
try {
if (document.forms[0].fullName.value == '') {
noNameException = new MissingValueException("First name is missing.");
throw noNameException;
}
} catch(e) {
if (e instanceofMissingValueException) {
document.write(e.message + "<br>");
document.write("Please contact the administrator.<br><br>");
} else {
document.write("An unexpected error has occurred.<br>");
document.write("Please contact the administrator.<br>");
document.write(e.message);
} } finally {
document.forms[0].submit();
} return 0; }
</script></head><body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

运算符instanceof可以同标准错误一起使用。JavaScript定义了以下标准的JavaScript错误类型:

EvalError:表明全局的eval函数使用错误。

RangeError:说明一个数值超过了所允许的值的范围。

ReferenceError:发现了一个非法的引用。

SyntaxError:发生了一个句法分析错误。

TypeError:一个操作数的实际类型与所预期的类型不同。

URIError:其中一个全局URI函数(编码URI或解码URI)使用错误。

列表G中的代码在一个catch语句中采用了TypeError类型。由于在引用字段名(document)的行中多了一个d,结果发生了一个打字错误(ddocument)。

列表G

以下为引用的内容:

<html><head>
<title>JS Test</title>
<script type="text/javascript">
function MissingValueException (errMsg) {
this.message = errMsg;
this.name="MissingValueException";
}
function doIt() {
try {
if (ddocument.forms[0].fullName.value == '') {
noNameException = new MissingValueException("First name is missing.");
throw noNameException;
}
} catch(e) {
if (e instanceofTypeError) {
document.write("Reference error while accessing First Name field.<br><br>");
document.write("Please contact the administrator.<br><br>");
document.write(e.message);
} else {
document.write("An unexpected error has occurred.<br><br>");
document.write("Please contact the administrator.<br><br>");
document.write(e.message);
} } finally {
document.forms[0].submit();
} return 0; }
</script></head>
<body><form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

处理所有的页面错误

另一个你可以自行支配的特性是window.onerror事件。和所有其他的JavaScript事件一样,你可以定义一个函数或者一条代码在事件被触发时运行。它可以用来处理或忽略错误。列表H中的页面显示了遇到的所有JavaScript错误的简单信息。因为指定的函数不存在,所以当点击按钮时,错误就发生了。列表I是用onerror事件来忽略所有的错误的。

列表H

以下为引用的内容:
<html><head>
<title>onError Test</title>
<script type="text/javascript">
function handleErrors() {
alert("A JavaScript error has occurred.");
return true;
}
window.onerror = handleErrors;
</script></head>
<body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">


</form></body></html>

列表I

以下为引用的内容:

<html><head>
<title>JS Test</title>
<script type="text/javascript">
function ignoreErrors() {
return true;
}
window.onerror = ignoreErrors;
</script></head>
<body><form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

谨慎处理

错误是每一个应用程序的一部分,但是适当的错误处理却不是。合理地运用JavaScript的错误处理特色和自动灵活的译码可以使用户的体验更顺畅,同时也让开发方的诊断工作变得更轻松。





上一篇:JavaScript 经典代码大全

下一篇: 大话“龟兔赛跑”--网页对象隐藏的特效
相关文章:
·Photoshop把偏色照片处理成仿手绘效果
·解决与HTTP 500 – 内部服务器错误错误信息有关的问题
·javascript实现语法分色编辑器
·极品飞车12显卡、处理器测试
·详解:FTP登陆错误问题完全分析
·JavaScript经典效果集锦(二)
·总结性知识:107个常用Javascript语句
相关软件:
·简明批处理教程
·宝石图片处理工具 V2006+
·易达第二代身份证照片处理系统(lab色彩版) V1.4
·最专业的照片处理软件PHOTOSHOP ISO CS2简体中文正版可升级
·余世维-职业经理人常犯的11种错误
·Javascript高级教程
·Javascript Menu MasterV2.5

特别声明:本站除部分特别声明禁止转载的专稿外的其他文章可以自由转载,但请务必注明出处和原始作者。文章版权归文章原始作者所有。对于被本站转载文章的个人和网站,我们表示深深的谢意。如果本站转载的文章有版权问题请联系编辑人员,我们尽快予以更正。
[打印本页] [关闭窗口] 转载请注明来源:http://www.viphot.com
| 帮助(?) | 版权声明 | 友情连接 | 关于我们 | 信息发布
Copyright 2007 www.viphot.com All Rights Reserved. 鄂ICP备05000083号Powered by:viphot