Core JavaScript 1.5 Guide:Exception Handling Statements:try...catch Statement
From MDC
Contents |
[edit] try...catch Statement
The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try...catch statement catches it.
The try...catch statement consists of a try block, which contains one or more statements, and zero or more catch blocks, containing statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch block. If no exception is thrown in the try block succeed, the catch block is skipped. The finally block executes after the try and catch blocks execute but before the statements following the try...catch statement.
The following example uses a try...catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number (1-12), an exception is thrown with the value InvalidMonthNo and the statements in the catch block set the monthName variable to unknown.
function getMonthName (mo) {
mo=mo-1; // Adjust month number for array index (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 {
// statements to try
monthName=getMonthName(myMonth) // function could throw exception
}
catch (e) {
monthName="unknown"
logMyErrors(e) // pass exception object to error handler
}
[edit] The catch Block
You can use a single catch block to handle all exceptions that may be generated in the try block, or you can use separate catch blocks each of which handles a particular type of exception.
Single catch Block
Use a single try...catch statement's catch block (recovery block) to execute error-handling code for any exceptions thrown in the try block.
A single catch block has the following syntax:
catch (catchID) {
statements
}
The catch block specifies an identifier (catchID in the preceding syntax) that holds the value specified by the throw statement; you can use this identifier to get information about the exception that was thrown. JavaScript creates this identifier when the catch block is entered; the identifier lasts only for the duration of the catch block; after the catch block finishes executing, the identifier is no longer available.
For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.
try {
throw "myException" // generates an exception
}
catch (e) {
// statements to handle any exceptions
logMyErrors(e) // pass exception object to error handler
}
Multiple catch Blocks
A single try statement can contain multiple conditional catch blocks, each of which handles a specific type of exception. In this case, the appropriate conditional catch block is entered only when the exception specified for that block is thrown. You can also include an optional catch-all catch block for all unspecified exceptions as the final catch block in the statement.
For example, the following function invokes three other functions (declared elsewhere), which validate its arguments. If a validation function determines that the component that it is checking is invalid, it returns 0, causing the caller to throw a particular exception.
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);
}
The conditional catch blocks route control to the appropriate exception handler.
try {
// function could throw three exceptions
getCustInfo("Lee", 1234, "lee@netscape.com")
}
catch (e if e == "InvalidNameException") {
// call handler for invalid names
bad_name_handler(e)
}
catch (e if e == "InvalidIdException") {
// call handler for invalid ids
bad_id_handler(e)
}
catch (e if e == "InvalidEmailException") {
// call handler for invalid email addresses
bad_email_handler(e)
}
catch (e){
// don't know what to do, but log it
logError(e)
}
[edit] The finally Block
The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception.
You can use the finally block to make your script fail gracefully when an exception occurs; for example, you may need to release a resource that your script has tied up. The following example opens a file and then executes statements that use the file (server-side JavaScript allows you to access files). If an exception is thrown while the file is open, the finally block closes the file before the script fails.
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
}
[edit] Nesting try...catch Statements
You can nest one or more try...catch statements. If an inner try...catch statement does not have a catch block, the enclosing try...catch statement's catch block is checked for a match.