JavaScript DHTML/Language Basics/throw — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 09:59, 26 мая 2010
Содержание
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>
Throws error in case of invalid data
<html>
<head>
<title>Try/Catch</title>
</head>
<body>
<form name="formexample" id="formexample" action="#">
<div id="valueDiv">Enter a value: <input id="value" name="value"></div>
<div><input id="submit" type="submit"></div>
</form>
<script type="text/javascript">
function checkValid() {
try {
var valueField = document.forms[0]["value"];
if (valueField.value != "A") {
throw "It"s not what I need";
}
}
catch(errorObject) {
alert(errorObject);
}
}
function init() {
document.forms[0].onsubmit = function() { return checkValid() };
}
window.onload = init;
</script>
</body>
</html>
Throw that error
<HTML>
<HEAD>
<TITLE>Throw that error!</TITLE>
<SCRIPT>
function throwError(errString) {
try {
throw new Error (42, errString);
}
catch(e){
alert("Error number: " + e.number + "; Description: " + e.description)
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="theForm">
Error text:
<INPUT type=text name=errText size=40>
<INPUT type=button name=btnThrow value="Throw it!" onClick="throwError(document.theForm.errText.value);">
</FORM>
</BODY>
</HTML>