你的位置:首页 > Java教程

[Java教程]javascript的错误处理

1 onerror事件,实例代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo2.aspx.cs" Inherits="WebApplication5.Demo2" %>

<script type="text/javascript">
function HandleError(sMessage,sURL,sLine) {
alert("出错了.\n"+"消息:"+sMessage+"\nURL:"+sURL+"\n出错行号:"+sLine);
return true;
}
window.onerror = HandleError;


</script>
<body onload="HandleLoad()"></body>

2 try ... catch... finally ,实例代码如下:

<script type="text/javascript">
try
{
//alert("ok");
windows.open("about:blank");
}
catch (exception) {
alert("an error processed");
}
finally {
alert("finally");
}

alert("ok");
</script>

注意:与JAVA/C#语言不同的是,不支持多重catch语句,但支持嵌套catch语句

实例代码如下:

<script type="text/javascript">
try
{
var a = document.getElementById("txtUser");
alert(a.value);
}
catch (ex) {
try
{
alert(ex.message);
}
catch (ex) {
alert(ex.message);
}
}
</script>

错误类型判断

方法1.通过name属性判断;

方法2:通过instanceof操作符

实例代码如下:

<script type="text/javascript">
try
{
var scriptStr="var a=0;var b=1;var c=a++b;alert(c)";
eval(scriptStr);
}
catch (ex) {
if (ex instanceof SyntaxError) {
alert("语法出错了");
}
}
</script>

抛出异常

ECMAScript还引入throw语句,用于抛出异常,语法如下:

throw error_object,

error_object可以是字符串,数字,布尔值或是实际的对象,如

throw "an error occurred";

throw 5009

throw true;

throw new Object();

throw new Error();

throw new Error("error");

throw new Error(10001,"error");

自定义异常:实例代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="js自定义异常.aspx.cs" Inherits="WebApplication5.js自定义异常" %>

<!DOCTYPE html>

<html <head runat="server">
<title></title>
<script type="text/javascript">
var EmailError = new Error(1001, "Email格式非法");
EmailError.name = "EmailFormatError";
EmailError.writeLog = function (funcname) {
var logstr = "error-code:" + this.number + "\n" + "error-message:" + this.message + "\n" + "error-type:" + this.name + "\n" + "error-func:" + funcname + "\n" + "error-time:" + (new Date()).toString();
alert(logstr);
}

function calc() {
var obj = document.getElementById("txtEmail");
try{
if(obj.value.indexOf("@")==-1)
{
throw EmailError;
}
else
{
alert("验证通过");
}
}
catch (ex) {
ex.writeLog("calc");
}

}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtEmail" />
<input type="button" id="btnCalc" value="Calc" onclick="calc()" />
</div>
</form>
</body>
</html>