try....catch....finally construct JS Home  <<  JS Reference  <<  try....catch....finally

Allows the programmer to construct code to deal with exceptions.

Description

The try....catch....finally construct allows us to put code, that might generate an exception, within a block and respond to any exceptions thrown.

  • The try statement must always be coded along with a catch or finally statement, or both.

Syntax

Signature Description
try {
  tryStatements
}
[catch (exceptionVariable1[ if condition1]) {
  catchStatements1
}]
...
[catch (exceptionVariableN[ if conditionN]) {
  catchStatementsN
}]
[finally {
  finallyStatements
}]
Creates a loop structure that with three optional expressions.

Parameters

Parameter Description
tryStatementsThe statements to be executed
exceptionVariable1...exceptionVariableNAn identifier to hold the exception object for the associated catch statement.
catchStatements1...catchStatementsNThe statements to be executed when a particular exception is caught.
condition1...conditionNConditional experssions.
finallyStatementsThe statements to be executed when all try statements have been processed. If present, these statements will always be executed.

Examples

The code below shows the try....catch....finally construct.



// Create our own error object.
function ourError(message) {  
  this.name = 'OurError';  
  this.message = message || 'Message Used When No Message Passed';
}   

// Inherit from the Error constructor.
ourError.prototype = new Error();  
ourError.prototype.constructor = ourError;   

// Throw an error and a message.
try {  
    throw new ourError('A Message we have passed');  
} catch (e) {  
    alert('Our Error: ' + e.name + ' Our Message: ' + e.message);
} finally {  
    alert('A finally statement will always be executed!');
}   

// Throw an error when condition is false.
var aNumber = 5;

if (aNumber < 5) {
    alert('This number is ok');
} else {
  
    try {  
      throw new ourError('Invalid number');  
    } catch (e) {  
      alert('Our Error: ' + e.name + ' Our Message: ' + e.message);
    }
}  

Press the button below to action the above code:

Related Tutorials

JavaScript Advanced Tutorials - Lesson 2 - Errors