[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/try...catch [Back]  [Original]

try...catch - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

try...catch

Baseline Widely available

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

js
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

catch try catch

catch try...catch catch try

catch

js
catch (catchID) {
  statements
}

catch catchID throw catch JavaScript catch catch

catch

js
try {
  throw "myException"; // 
} catch (e) {
  // 
  logMyErrors(e); // 
}

catch try catch catch catch catch

0

js
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

js
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

finally try catch try...catch finally catch finally

finally Script Script JavaScript finally Script

js
openMyFile();
try {
  writeMyFile(theData); // 
} catch (e) {
  handleError(e); // 
} finally {
  closeMyFile(); // 
}

try...catch

try...catch try...catch catch try...catch catch

Error

name message name DOMException Errormessage

catch

js
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 
}
page(Doc) not found /zh-TW/docs/Core_JavaScript_1.5_::throw_

Web Proxy Viewer  |  New URL  |  Original Page