| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/try...catch | [Back] [Original] |
Get to know MDN better
This feature is well established and works across many devices and browser versions. Its been available across browsers since 20157.
try...catch try...catch
try...catch try catch try try catch try try catch try catch finally try catch try...catch
try...catch (1-12) InvalidMonthNo catch monthName unknown
function getMonthName(mo) {
mo = mo - 1; // (1=Jan, 12=Dec)
var months = new Array(
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
);
if (months[mo] != null) {
return months[mo];
} else {
throw "InvalidMonthNo";
}
}
try {
//
monthName = getMonthName(myMonth); //
} catch (e) {
monthName = "unknown";
logMyErrors(e); //
}
catch try catch
catch
try...catch catch try
catch
catch (catchID) {
statements
}
catch catchID throw catch JavaScript catch catch
catch
try {
throw "myException"; //
} catch (e) {
//
logMyErrors(e); //
}
catch
try catch catch catch catch
0
function getCustInfo(name, id, email) {
var n, i, e;
if (!validate_name(name)) throw "InvalidNameException";
else n = name;
if (!validate_id(id)) throw "InvalidIdException";
else i = id;
if (!validate_email(email)) throw "InvalidEmailException";
else e = email;
cust = n + " " + i + " " + e;
return cust;
}
catch
try {
//
getCustInfo("Lee", 1234, "lee@netscape.com")
}
catch (e if e == "InvalidNameException") {
//
bad_name_handler(e)
}
catch (e if e == "InvalidIdException") {
// ID
bad_id_handler(e)
}
catch (e if e == "InvalidEmailException") {
//
bad_email_handler(e)
}
catch (e){
//
logError(e)
}
finally try catch try...catch finally catch finally
finally Script Script JavaScript finally Script
openMyFile();
try {
writeMyFile(theData); //
} catch (e) {
handleError(e); //
} finally {
closeMyFile(); //
}
try...catch try...catch catch try...catch catch
name message name DOMException Errormessage
catch
function doSomethingErrorProne () {
if (ourCodeMakesAMistake()) {
throw (new Error('The message'));
}
else {
doSomethingToGetAJavascriptError();
}
}
....
try {
doSomethingErrorProne();
}
catch (e) {
alert(e.name);// 'Error'
alert(e.message); // 'The message' JavaScript
}
This page was last modified on 2025716 by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |