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 acatch
orfinally
statement, or both.
Syntax
Signature | Description |
---|---|
try { | Creates a loop structure that with three optional expressions. |
Parameters
Parameter | Description |
---|---|
tryStatements | The statements to be executed |
exceptionVariable1...exceptionVariableN | An identifier to hold the exception object for the associated catch statement. |
catchStatements1...catchStatementsN | The statements to be executed when a particular exception is caught. |
condition1...conditionN | Conditional experssions. |
finallyStatements | The 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);
}
}
Related Tutorials
JavaScript Advanced Tutorials - Lesson 2 - Errors