Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1086373 of Control flow and error handling

  • Revision slug: Web/JavaScript/Guide/Control_flow_and_error_handling
  • Revision title: Control flow and error handling
  • Revision id: 1086373
  • Created:
  • Creator: haarabi
  • Is current revision? No
  • Comment matching code style in the document

Revision Content

{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}

JavaScript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application. This chapter provides an overview of these statements.

The JavaScript reference contains exhaustive details about the statements in this chapter. The semicolon (;) character is used to separate statements in JavaScript code.

Any JavaScript expression is also a statement. See Expressions and operators for complete information about expressions.

Block statement

The most basic statement is a block statement that is used to group statements. The block is delimited by a pair of curly brackets:

{
  statement_1;
  statement_2;
  .
  .
  .
  statement_n;
}

Example

Block statements are commonly used with control flow statements (e.g. if, for, while).

while (x < 10) {
  x++;
}

Here, { x++; } is the block statement.

Important: JavaScript prior to ECMAScript2015 does not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not define a scope. "Standalone" blocks in JavaScript can produce completely different results from what they would produce in C or Java. For example:

var x = 1;
{
  var x = 2;
}
console.log(x); // outputs 2

This outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block. In C or Java, the equivalent code would have outputted 1.

Starting with ECMAScript2015, the let variable declaration is block scoped. See the {{jsxref("Statements/let", "let")}} reference page for more information.

Conditional statements

A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if...else and switch.

if...else statement

Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false. An if statement looks as follows:

if (condition) {
  statement_1;
} else {
  statement_2;
}

condition can be any expression that evaluates to true or false. See Boolean for an explanation of what evaluates to true and false. If condition evaluates to true, statement_1 is executed; otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements.

You may also compound the statements using else if to have multiple conditions tested in sequence, as follows:

if (condition_1) {
  statement_1;
} else if (condition_2) {
  statement_2;
} else if (condition_n) {
  statement_n;
} else {
  statement_last;
} 

In the case of multiple conditions only the first logical condition which evaluates to true will be executed. To execute multiple statements, group them within a block statement ({ ... }) . In general, it's good practice to always use block statements, especially when nesting if statements:

if (condition) {
  statement_1_runs_if_condition_is_true;
  statement_2_runs_if_condition_is_true;
} else {
  statement_3_runs_if_condition_is_false;
  statement_4_runs_if_condition_is_false;
}
It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
if (x = y) {
  /* statements here */
}

If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:

if ((x = y)) {
  /* statements here */
}

Falsy values

The following values evaluate to false (also known as {{Glossary("Falsy")}} values):

  • false
  • undefined
  • null
  • 0
  • NaN
  • the empty string ("")

All other values, including all objects, evaluate to true when passed to a conditional statement.

Do not confuse the primitive boolean values true and false with the true and false values of the {{jsxref("Boolean")}} object. For example:

var b = new Boolean(false);
if (b) // this condition evaluates to true
if (b == true) // this condition evaluates to false

Example

In the following example, the function checkData returns true if the number of characters in a Text object is three; otherwise, it displays an alert and returns false.

function checkData() {
  if (document.form1.threeChar.value.length == 3) {
    return true;
  } else {
    alert("Enter exactly three characters. " +
    document.form1.threeChar.value + " is not valid.");
    return false;
  }
}

switch statement

A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A switch statement looks as follows:

switch (expression) {
  case label_1:
    statements_1
    [break;]
  case label_2:
    statements_2
    [break;]
    ...
  default:
    statements_def
    [break;]
}

The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. If no matching label is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

The optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

Example

In the following example, if fruittype evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program terminates switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

switch (fruittype) {
  case "Oranges":
    console.log("Oranges are $0.59 a pound.");
    break;
  case "Apples":
    console.log("Apples are $0.32 a pound.");
    break;
  case "Bananas":
    console.log("Bananas are $0.48 a pound.");
    break;
  case "Cherries":
    console.log("Cherries are $3.00 a pound.");
    break;
  case "Mangoes":
    console.log("Mangoes are $0.56 a pound.");
    break;
  case "Papayas":
    console.log("Mangoes and papayas are $2.79 a pound.");
    break;
  default:
   console.log("Sorry, we are out of " + fruittype + ".");
}
console.log("Is there anything else you'd like?");

Exception handling statements

You can throw exceptions using the throw statement and handle them using the try...catch statements.

Exception types

Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects are created equal. While it is fairly common to throw numbers or strings as errors it is frequently more effective to use one of the exception types specifically created for this purpose:

throw statement

Use the throw statement to throw an exception. When you throw an exception, you specify the expression containing the value to be thrown:

throw expression;

You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:

throw "Error2";   // String type
throw 42;         // Number type
throw true;       // Boolean type
throw {toString: function() { return "I'm an object!"; } };
Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object myUserException of type UserException and uses it in a throw statement.
// 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

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 one 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, 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 = ["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
}

The catch block

You can use a catch block to handle all exceptions that may be generated in the try block.

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
}

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
}

If the finally block returns a value, this value becomes the return value of the entire try-catch-finally production, regardless of any return statements in the try and catch blocks:

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

Overwriting of return values by the finally block also applies to exceptions thrown or re-thrown inside of the catch block:

function f() {
  try {
    throw "bogus";
  } catch(e) {
    console.log('caught inner "bogus"');
    throw e; // this throw statement is suspended until 
             // finally block has completed
  } finally {
    return false; // overwrites the previous "throw"
  }
  // "return false" is executed now
}

try {
  f();
} catch(e) {
  // this is never reached because the throw inside
  // the catch is overwritten
  // by the return in finally
  console.log('caught outer "bogus"');
}

// OUTPUT
// caught inner "bogus"

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.

Utilizing Error objects

Depending on the type of error, you may be able to use the 'name' and 'message' properties to get a more refined message. 'name' provides the general class of Error (e.g., 'DOMException' or 'Error'), while 'message' generally provides a more succinct message than one would get by converting the error object to a string.

If you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn't discriminate between your own exceptions and system ones), you can use the Error constructor. For example:

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)
}

Promises

Starting with ECMAScript2015, JavaScript gains support for {{jsxref("Promise")}} objects allowing you to control the flow of deferred and asynchronous operations.

A Promise is in one of these states:

  • pending: initial state, not fulfilled or rejected.
  • fulfilled: successful operation
  • rejected: failed operation.
  • settled: the Promise is either fulfilled or rejected, but not pending.

Loading an image with XHR

A simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely. Here is the uncommented version, showing the Promise flow so that you can get an idea:

function imgLoad(url) {
  return new Promise(function(resolve, reject) {
    var request = new XMLHttpRequest();
    request.open('GET', url);
    request.responseType = 'blob';
    request.onload = function() {
      if (request.status === 200) {
        resolve(request.response);
      } else {
        reject(Error('Image didn\'t load successfully; error code:' 
                     + request.statusText));
      }
    };
    request.onerror = function() {
      reject(Error('There was a network error.'));
    };
    request.send();
  });
}

For more detailed information, see the {{jsxref("Promise")}} reference page.

{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}

Revision Source

<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}</div>

<p class="summary">JavaScript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application. This chapter provides an overview of these statements.</p>

<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript reference</a> contains exhaustive details about the statements in this chapter. The semicolon (<code>;</code>) character is used to separate statements in JavaScript code.</p>

<p>Any JavaScript expression is also a statement. See <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a> for complete information about expressions.</p>

<h2 id="Block_statement">Block statement</h2>

<p>The most basic statement is a block statement that is used to group statements. The block is delimited by a pair of curly brackets:</p>

<pre class="syntaxbox">
{
  statement_1;
  statement_2;
  .
  .
  .
  statement_n;
}
</pre>

<h3 id="Example"><strong>Example</strong></h3>

<p>Block statements are commonly used with control flow statements (e.g. <code>if</code>, <code>for</code>, <code>while</code>).</p>

<pre class="brush: js">
while (x &lt; 10) {
  x++;
}
</pre>

<p>Here, <code>{ x++; }</code> is the block statement.</p>

<p><strong>Important</strong>: JavaScript prior to ECMAScript2015&nbsp;does <strong>not</strong> have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not define a scope. "Standalone" blocks in JavaScript can produce completely different results from what they would produce in C or Java. For example:</p>

<pre class="brush: js">
var x = 1;
{
  var x = 2;
}
console.log(x); // outputs 2
</pre>

<p>This outputs 2 because the <code>var x</code> statement within the block is in the same scope as the <code>var x</code> statement before the block. In C or Java, the equivalent code would have outputted 1.</p>

<p>Starting with ECMAScript2015, the <code>let</code> variable declaration is block scoped. See the {{jsxref("Statements/let", "let")}} reference page for more information.</p>

<h2 id="Conditional_statements">Conditional statements</h2>

<p>A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: <code>if...else</code> and <code>switch</code>.</p>

<h3 id="if...else_statement"><code>if...else</code> statement</h3>

<p>Use the <code>if</code> statement to execute a statement if a logical condition is true. Use the optional <code>else</code> clause to execute a statement if the condition is false. An <code>if</code> statement looks as follows:</p>

<pre class="syntaxbox">
if (condition) {
  statement_1;
} else {
  statement_2;
}</pre>

<p><code>condition</code> can be any expression that evaluates to true or false. See <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description">Boolean</a> for an explanation of what evaluates to <code>true</code> and <code>false</code>. If <code>condition</code> evaluates to true, <code>statement_1</code> is executed; otherwise, <code>statement_2</code> is executed. <code>statement_1</code> and <code>statement_2</code> can be any statement, including further nested <code>if</code> statements.</p>

<p>You may also compound the statements using <code>else if</code> to have multiple conditions tested in sequence, as follows:</p>

<pre class="syntaxbox">
if (condition_1) {
  statement_1;
} else if (condition_2) {
&nbsp; statement_2;
} else if (condition_n) {
&nbsp; statement_n;
} else {
&nbsp; statement_last;
}&nbsp;
</pre>

<p>In the case of multiple conditions only&nbsp;the first logical condition which evaluates to true will be executed.&nbsp;To execute multiple statements, group them within a block statement (<code>{ ... }</code>) . In general, it's good practice to always use block statements, especially when nesting <code>if</code> statements:</p>

<pre class="syntaxbox">
if (condition) {
  statement_1_runs_if_condition_is_true;
  statement_2_runs_if_condition_is_true;
} else {
  statement_3_runs_if_condition_is_false;
  statement_4_runs_if_condition_is_false;
}
</pre>

<div>It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:</div>

<pre class="example-bad brush: js">
if (x = y) {
  /* statements here */
}
</pre>

<p>If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:</p>

<pre class="brush: js">
if ((x = y)) {
  /* statements here */
}
</pre>

<h4 id="Falsy_values">Falsy values</h4>

<p>The following values evaluate to false (also known as {{Glossary("Falsy")}} values):</p>

<ul>
 <li><code>false</code></li>
 <li><code>undefined</code></li>
 <li><code>null</code></li>
 <li><code>0</code></li>
 <li><code>NaN</code></li>
 <li>the empty string (<code>""</code>)</li>
</ul>

<p>All other values, including all objects, evaluate to true when passed to a conditional statement.</p>

<p>Do not confuse the primitive boolean values <code>true</code> and <code>false</code> with the true and false values of the {{jsxref("Boolean")}} object. For example:</p>

<pre class="brush: js">
var b = new Boolean(false);
if (b) // this condition evaluates to true
if (b == true) // this condition evaluates to false
</pre>

<h4 id="Example_2"><strong>Example</strong></h4>

<p>In the following example, the function <code>checkData</code> returns <code>true</code> if the number of characters in a <code>Text</code> object is three; otherwise, it displays an alert and returns <code>false</code>.</p>

<pre class="brush: js">
function checkData() {
  if (document.form1.threeChar.value.length == 3) {
    return true;
  } else {
    alert("Enter exactly three characters. " +
    document.form1.threeChar.value + " is not valid.");
    return false;
  }
}
</pre>

<h3 id="switch_statement"><code>switch</code> statement</h3>

<p>A <code>switch</code> statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A <code>switch</code> statement looks as follows:</p>

<pre class="syntaxbox">
switch (expression) {
  case label_1:
    statements_1
    [break;]
  case label_2:
    statements_2
    [break;]
    ...
  default:
    statements_def
    [break;]
}
</pre>

<p>The program first looks for a <code>case</code> clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. If no matching label is found, the program looks for the optional <code>default</code> clause, and if found, transfers control to that clause, executing the associated statements. If no <code>default</code> clause is found, the program continues execution at the statement following the end of <code>switch</code>. By convention, the <code>default</code> clause is the last clause, but it does not need to be so.</p>

<p>The optional <code>break</code> statement associated with each <code>case</code> clause ensures that the program breaks out of <code>switch</code> once the matched statement is executed and continues execution at the statement following switch. If <code>break</code> is omitted, the program continues execution at the next statement in the <code>switch</code> statement.</p>

<h4 id="Example_3"><strong>Example</strong></h4>

<p>In the following example, if <code>fruittype</code> evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When <code>break</code> is encountered, the program terminates <code>switch</code> and executes the statement following <code>switch</code>. If <code>break</code> were omitted, the statement for case "Cherries" would also be executed.</p>

<pre class="brush: js">
switch (fruittype) {
  case "Oranges":
    console.log("Oranges are $0.59 a pound.");
    break;
  case "Apples":
    console.log("Apples are $0.32 a pound.");
    break;
  case "Bananas":
    console.log("Bananas are $0.48 a pound.");
    break;
  case "Cherries":
    console.log("Cherries are $3.00 a pound.");
    break;
  case "Mangoes":
    console.log("Mangoes are $0.56 a pound.");
    break;
  case "Papayas":
    console.log("Mangoes and papayas are $2.79 a pound.");
    break;
  default:
   console.log("Sorry, we are out of " + fruittype + ".");
}
console.log("Is there anything else you'd like?");</pre>

<h2 id="Exception_handling_statements">Exception handling statements</h2>

<p>You can throw exceptions using the <code>throw</code> statement and handle them using the <code>try...catch</code> statements.</p>

<ul>
 <li><a href="#throw_statement"><code>throw</code> statement</a></li>
 <li><a href="#try...catch_statement"><code>try...catch</code> statement</a></li>
</ul>

<h3 id="Exception_types">Exception types</h3>

<p>Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects are created equal. While it is fairly common to throw numbers or strings as errors it is frequently more effective to use one of the exception types specifically created for this purpose:</p>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects#Fundamental_objects">ECMAScript exceptions</a></li>
 <li>{{domxref("DOMException")}} and&nbsp;{{domxref("DOMError")}}</li>
</ul>

<h3 id="throw_statement"><code>throw</code> statement</h3>

<p>Use the <code>throw</code> statement to throw an exception. When you throw an exception, you specify the expression containing the value to be thrown:</p>

<pre class="syntaxbox">
throw expression;
</pre>

<p>You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:</p>

<pre class="brush: js">
throw "Error2";   // String type
throw 42;         // Number type
throw true;       // Boolean type
throw {toString: function() { return "I'm an object!"; } };
</pre>

<div class="note"><strong>Note:</strong> You can specify an object when you throw an exception. You can then reference the object's properties in the <code>catch</code> block. The following example creates an object <code>myUserException</code> of type <code>UserException</code> and uses it in a throw statement.</div>

<pre class="brush: js">
// 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");</pre>

<h3 id="try...catch_statement"><code>try...catch</code> statement</h3>

<p>The <code>try...catch</code> 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 <code>try...catch</code> statement catches it.</p>

<p>The <code>try...catch</code> statement consists of a <code>try</code> block, which contains one or more statements, and one or more <code>catch</code> blocks, containing statements that specify what to do if an exception is thrown in the <code>try</code> block. That is, you want the <code>try</code> block to succeed, and if it does not succeed, you want control to pass to the <code>catch</code> block. If any statement within the <code>try</code> block (or in a function called from within the <code>try</code> block) throws an exception, control immediately shifts to the <code>catch</code> block. If no exception is thrown in the <code>try</code> block, the <code>catch</code> block is skipped. The <code>finally</code> block executes after the <code>try</code> and <code>catch</code> blocks execute but before the statements following the <code>try...catch</code> statement.</p>

<p>The following example uses a <code>try...catch</code> 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 <code>"InvalidMonthNo"</code> and the statements in the <code>catch</code> block set the <code>monthName</code> variable to <code>unknown</code>.</p>

<pre class="brush: js">
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 -&gt; your own function
}
</pre>

<h4 id="The_catch_Block" name="The_catch_Block">The <code>catch</code> block</h4>

<p>You can use a <code>catch</code> block to handle all exceptions that may be generated in the <code>try</code> block.</p>

<pre class="syntaxbox">
catch (catchID) {
  statements
}
</pre>

<p>The <code>catch</code> block specifies an identifier (<code>catchID</code> in the preceding syntax) that holds the value specified by the <code>throw</code> statement; you can use this identifier to get information about the exception that was thrown. JavaScript creates this identifier when the <code>catch</code> block is entered; the identifier lasts only for the duration of the <code>catch</code> block; after the <code>catch</code> block finishes executing, the identifier is no longer available.</p>

<p>For example, the following code throws an exception. When the exception occurs, control transfers to the <code>catch</code> block.</p>

<pre class="brush: js">
try {
  throw "myException"; // generates an exception
}
catch (e) {
  // statements to handle any exceptions
  logMyErrors(e); // pass exception object to error handler
}
</pre>

<h4 id="The_finally_block">The <code>finally</code> block</h4>

<p>The <code>finally</code> block contains statements to execute after the <code>try</code> and <code>catch</code> blocks execute but before the statements following the <code>try...catch</code> statement. The <code>finally</code> block executes whether or not an exception is thrown. If an exception is thrown, the statements in the <code>finally</code> block execute even if no <code>catch</code> block handles the exception.</p>

<p>You can use the <code>finally</code> 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 <code>finally</code> block closes the file before the script fails.</p>

<pre class="brush: js">
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
}
</pre>

<p>If the <code>finally</code> block returns a value, this value becomes the return value of the entire <code>try-catch-finally</code> production, regardless of any <code>return</code> statements in the <code>try</code> and <code>catch</code> blocks:</p>

<pre class="brush: js">
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
</pre>

<p>Overwriting of return values&nbsp;by the <code>finally</code> block also applies to exceptions thrown or re-thrown inside of the <code>catch</code> block:</p>

<pre class="brush: js">
function f() {
  try {
    throw "bogus";
  } catch(e) {
    console.log('caught inner "bogus"');
    throw e; // this throw statement is suspended until 
             // finally block has completed
  } finally {
    return false; // overwrites the previous "throw"
  }
  // "return false" is executed now
}

try {
  f();
} catch(e) {
  // this is never reached because the throw inside
  // the catch is overwritten
  // by the return in finally
  console.log('caught outer "bogus"');
}

// OUTPUT
// caught inner "bogus"</pre>

<h4 id="Nesting_try...catch_Statements" name="Nesting_try...catch_Statements">Nesting try...catch statements</h4>

<p>You can nest one or more <code>try...catch</code> statements. If an inner <code>try...catch</code> statement does not have a <code>catch</code> block, the enclosing <code>try...catch</code> statement's <code>catch</code> block is checked for a match.</p>

<h3 id="Utilizing_Error_objects">Utilizing <code>Error</code> objects</h3>

<p>Depending on the type of error, you may be able to use the 'name' and 'message' properties to get a more refined message. 'name' provides the general class of Error (e.g., 'DOMException' or 'Error'), while 'message' generally provides a more succinct message than one would get by converting the error object to a string.</p>

<p>If you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn't discriminate between your own exceptions and system ones), you can use the Error constructor. For example:</p>

<pre class="brush: js">
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)
}</pre>

<h2 id="Promises">Promises</h2>

<p>Starting with ECMAScript2015, JavaScript gains support for {{jsxref("Promise")}} objects allowing you to control the flow of deferred and asynchronous operations.</p>

<p>A <code>Promise</code> is in one of these&nbsp;states:</p>

<ul>
 <li><em>pending</em>: initial state, not fulfilled or rejected.</li>
 <li><em>fulfilled</em>: successful operation</li>
 <li><em>rejected</em>: failed operation.</li>
 <li><em>settled</em>:&nbsp;the Promise is either fulfilled or rejected, but not pending.</li>
</ul>

<p><img alt="" src="https://mdn.mozillademos.org/files/8633/promises.png" style="height:297px; width:801px" /></p>

<h3 id="Loading_an_image_with_XHR">Loading an image with XHR</h3>

<p>A simple example using <code>Promise</code> and <code><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code> to load an image is available at the MDN GitHub<a href="https://github.com/mdn/promises-test/blob/gh-pages/index.html"> promise-test</a> repository. You can also <a href="https://mdn.github.io/promises-test/">see it in action</a>. Each step is commented and allows you to follow the Promise and XHR architecture closely. Here is the uncommented version, showing the <code>Promise</code> flow so that you can get an idea:</p>

<pre class="brush: js">
function imgLoad(url) {
  return new Promise(function(resolve, reject) {
    var request = new XMLHttpRequest();
    request.open('GET', url);
    request.responseType = 'blob';
    request.onload = function() {
      if (request.status === 200) {
        resolve(request.response);
      } else {
        reject(Error('Image didn\'t load successfully; error code:' 
                     + request.statusText));
      }
    };
    request.onerror = function() {
      reject(Error('There was a network error.'));
    };
    request.send();
  });
}</pre>

<p>For more detailed information, see the {{jsxref("Promise")}} reference page.</p>

<div>{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}</div>
Revert to this revision