exception handling
Exception type
-
ECMAScript exceptions -
DOMException -
nsIXPCException (XPConnect)
Throw statement
throw expression;
throw "Error2"; // String type throw 42; // Number type throw true; // Boolean type throw {toString: function() { return "I'm an object!"; } };
// Create an object type UserException function UserException (message){ this.message=message; this.name="UserException"; } // Make the exception convert to a pretty string when used as // a string (e.g. by the error console) UserException.prototype.toString = function (){ return this.name + ': "' + this.message + '"'; } // Create an instance of the object type and throw it throw new UserException("Value too high");
try... Catch statement
function getMonthName(mo) { mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec) var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul", "Aug","Sep","Oct","Nov","Dec"]; if (months[mo]) { return months[mo]; } else { throw "InvalidMonthNo"; // throw keyword is used here } } try { // statements to try monthName = getMonthName(myMonth); // function could throw exception } catch (e) { monthName = "unknown"; logMyErrors(e); // pass exception object to error handler -> your own function }
Snap Block
catch (catchID) { statements }
try { throw "myException" // generates an exception } catch (e) { // statements to handle any exceptions logMyErrors(e) // pass exception object to error handler }
End block
openMyFile(); try { writeMyFile(theData); // This may throw a error }catch(e){ handleError(e); // If we got a error we handle it }finally { closeMyFile(); // always close the resource }
function f() { try { console.log(0); throw "bogus"; } catch(e) { console.log(1); return true; // this return statement is suspended // until finally block has completed console.log(2); // not reachable } finally { console.log(3); return false; // overwrites the previous "return" console.log(4); // not reachable } // "return false" is executed now console.log(5); // not reachable } f(); // console 0, 1, 3; returns false
Error matching object
function doSomethingErrorProne () { if (ourCodeMakesAMistake()) { throw (new Error('The message')); } else { doSomethingToGetAJavascriptError(); } } .... try { doSomethingErrorProne(); } catch (e) { console.log(e.name); // logs 'Error' console.log(e.message); // logs 'The message' or a JavaScript error message) }