Try/Catch
The try...catch...finally
statement defines three blocks of code. The try
block contains code that is tested for possible errors. If an error occurs, the catch
block handles the exception. Finally, the finally
block contains code that will execute regardless of whether an error occurred, ensuring that cleanup or final actions take place.
All try
blocks must be followed by either catch
, finally
, or both.
Syntax
try {// Statements here are executed until an exception is thrown} catch (err) {// Statements here are executed once an exception is thrown in the try block} finally {// Statements here are always executed regardless of any exception}
The following example shows the try...catch...finally
statement in action:
The Error Object
In the above, err
is an optional variable with an error object for the associated catch
block.
This object contains information about the thrown exception and is only available in the scope of the catch
block.
The error object has two properties:
name
: Sets or returns an error name. (Type of error)message
: Sets or returns an error message. (Description of specific instance)
The following types of error can be returned by the name
property:
RangeError
: A number “out of range” has occurredReferenceError
: An illegal reference has occurredSyntaxError
: A syntax error has occurredTypeError
: A type error has occurredURIError
: An error inencodeURI()
has occurred
The throw
Statement
The throw
statement can be used to throw user-defined exceptions. The custom exception can be any JavaScript type, including String
, Number
, Boolean
or Object
, which will be caught by the next outer catch block.
This can be useful for things like validating input:
var input = 25;try {if (input < 10) {throw 'too small!';} else if (input > 20) {throw 'too big!';} else {console.log('Input was ' + input);}} catch (e) {console.log('Input was ' + e);}
The throw
statement can also re-throw an error object caught by a catch
block. This can be useful if only certain types of error should be handled:
try {// Series of statements} catch (e) {if (e instanceof RangeError) {// Here, any instance of a RangeError exception is handled} else {// Re-throw any other exceptionsthrow e;}}
Codebyte Example
All contributors
- StevenSwiniarski
- Anonymous contributor
- itispragativerma6560850080
- Anonymous contributor
- christian.dinh
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Skill path
Create a Back-End App with JavaScript
Learn how to build back-end web APIs using Express.js, Node.js, SQL, and a Node.js-SQLite database library.Includes 8 CoursesWith CertificateBeginner Friendly30 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours