網頁特效 try...catch 異常處理詳解
文法
try{
statement1
}catch(exception){
statement2
}
它可以用來處理全部或一些錯誤,可以發生在一個指令碼。
如果一個錯誤並不是由一試…趕上聲明,它是通過對所以其他報表能夠處理的錯誤。
如果沒有其他報表處理錯誤時,它傳遞給瀏覽器來處理。
statement1可能發生的地方,這是一個錯誤,而statement2是用來處理錯誤。
當一個錯誤發生,其值傳遞給抓住丟分的聲明中,並儲存在例外。
<html>
<head>
<title>using a try..catch statement</title>
<script language="javascript">
<!--
function myerrorhandler(data){
try{
try{
if(data == "string"){
throw "e0";
}else{
throw "e1";
}
}catch(e){
if(e == "e0"){
return("error (" + e + "): entry must be numeric.");
}else{
throw e;
}
}
}catch (e){
return("error (" + e + "): entry was invalid.");
}
}
function processdata(form){
if(isnan(parseint(form.mytext.value))){
alert(myerrorhandler("string"));
}else{
alert("you have correctly entered a number");
}
}
-->
</script>
</head>
<body>
<form name="myform">
please enter a number:
<input type=text size=10 value="" name="mytext">
<input type=button value="process" name="mybutton" onclick='processdata(this.form)'>
</form>
</body>
</html>
錯誤處理. catch that error
<html>
<head>
<title>catch that error!</title>
<script>
function catcherror(errstring) {
try {
try {
if (errstring == -1)
throw new error (-1, "errstring is -1!");
else
throw new error (0, "errstring is not -1!");
}
catch(e) {
if (e.number == -1)
return (e.description + " got this one!");
else
throw e;
}
}
catch (e){
return(e.description + " this one not handled here!");
}
}
</script>
</head>
<body>
<form name="theform">
<input type=text name=errtext value="-1">
<input type=button name=btnthrow value="catch it!" onclick="alert(catcherror(document.theform.errtext.value));">
</form>
</body>
</html>
異常處理和嘗試 exception handling with try/catch
<html>
<head>
<title></title>
<script language="javascript" type="text/javascript">
function getmonthname (monthnumber) {
throw "invalidmonthnumber"
}
try {
alert(getmonthname(13))
}
catch (exception) {
alert("an " + exception + " exception was encountered. please contact the program vendor.")
}
</script>
<body>
</body>
</html>