try statements, catch, [finally] Last updated: 21. Mar 2024

Keyword

The JavaScript try statement executes a block of code, catches errors if they occur using catch, and includes an optional finally block that executes regardless of the outcome.

Parameters

Name Type Description
statements code block The main code block or statements to be executed.
catch code block Code block that handles errors or exceptions thrown in the 'statements' block.
finally (optional) code block Code block that executes after the try and catch blocks, regardless of the result.

Returns

Does not return anything.

Example

Code example (JS)

JS is normal JavaScript either running in the browser or on the Docly™ server.
try {
  // Code that may throw an error
  write("Trying to execute this code.\n");
  throw new Error("Oops! An error occurred.");
} catch (error) {
  // Code to run if an error occurs
  write("Error caught: " + error.message + "\n");
} finally {
  // Code that will run regardless of the try / catch outcome
  write("This code runs no matter what.");
}

Output

The JS code above produces the output shown below:
Trying to execute this code.
Error caught: Oops! An error occurred.
This code runs no matter what.