首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

对try. catch 的1点理解

2012-08-31 
对try... catch 的一点理解script languageJavaScript typetext/javascript!--try{var n promp

对try... catch 的一点理解
<script language="JavaScript" type="text/javascript">
<!--
try{
var n = prompt('请输入一个正整数')
var f = 我的函数(n)
alert(f)
}
catch(ex){//ex引用抛出的Error对象或其他值;

if(ex instanceof NonePositiveError){//判断ex是否是NonePositiveError对象的一个实例;
alert(ex.message)
}
else if(ex instanceof Nerror){//同上,判断ex是不是Nerror对象的一个实例;
alert(ex.message)
}
else{
throw (ex)
}
}

function NonePositiveError(n){
n = n || '';
this.message = "输入的数字" + n + "不是正整数!";
}
NonePositiveError.prototype = new Error();

function Nerror(){
this.message = "输入的不是一个数字!";
}
Nerror.prototype = new Error();
function 我的函数(n){
n = parseInt(n);
if(isNaN(n)){
throw (new Nerror())//抛出错误;
}
else if(n <= 0){
throw (new NonePositiveError(n))//抛出错误;
}
return n <=1 ? 1 : n * 我的函数(n - 1);
}
//-->
</script>
对于抛出的错误对象我们可以自己定义,定义的格式如下:
function def(){....} def.prototype = new Error();

热点排行