javascript 中的try catch应用总结实例代码:<script language="Javascript">
try
{
throw new Error(10,"asdasdasd")
}
catch (e)
{
alert(e.message);
alert(e.description)
alert(e.number)
alert(e.name)
throw new Error(10,"asdasdasd")
}
</script>在Javascript可以使用try...catch来进行异常处理。例如: try {
foo.bar();
} catch (e) {
alert(e.name + ": " + e.message);
}目前我们可能得到的系统异常主要包含以下6种:EvalError: raised when an error occurs executing code in eval()
RangeError: raised when a numeric variable or parameter is outside of its valid range
ReferenceError: raised when de-referencing an invalid reference
SyntaxError: raised when a syntax error occurs while parsing code in eval()
TypeError: raised when a variable or parameter is not a valid type
URIError: raised when encodeURI() or decodeURI() are passed invalid parameters上面的六种异常对象都继承自Error对象。他们都支持以下两种构造方法:new Error();
new Error("异常信息");手工抛出异常的方法如下:try {
throw new Error("Whoops!");
} catch (e) {
alert(e.name + ": " + e.message);
}如要判断异常信息的类型,可在catch中进行判断:try {
foo.bar();
} catch (e) {
if (e instanceof EvalError) {
alert(e.name + ":" + e.message);
}
else if (e instanceof RangeError) {
alert(e.name + ": " + e.message);
}
// etc
}
更多相关内容: