Skip to content

try

In JavaScript, the try keyword starts a statement that runs a block of code and handles any exception the block throws. The block must be followed by a catch clause, a finally clause, or both, and all three parts must be blocks in braces.

When a statement in the try block, or a function it calls, throws, the rest of the block is skipped and control moves to catch. If nothing throws, catch is skipped. The finally block runs in both cases. Exceptions come from runtime errors and from the throw statement. An exception that an inner try statement doesn’t catch moves on to the nearest enclosing one.

A try block catches a rejected promise only when code inside it waits for the promise with await. A callback that runs later, such as one passed to setTimeout(), runs outside the try block.

JavaScript try Keyword Syntax

A try block needs a catch block, a finally block, or both:

Language: JavaScript Syntax
try {
  <statements>
} catch [(<binding>)] {
  <statements>
} [finally {
  <statements>
}]

try {
  <statements>
} finally {
  <statements>
}

JavaScript try Keyword Examples

A try block lets parseSettings() recover from invalid JSON:

Language: JavaScript
> function parseSettings(text) {
…   try {
…     return JSON.parse(text);
…   } catch (error) {
…     console.log(`Invalid settings: ${error.message}`);
…     return {};
…   }
… }
undefined

> parseSettings('{"theme": "dark"}')
{ theme: 'dark' }

> parseSettings("")
Invalid settings: Unexpected end of JSON input
{}

The second call makes JSON.parse() throw, so the return in the try block never completes, and the catch block logs the error message and returns an empty object.

JavaScript try Keyword Use Cases

  • Handling errors from parsing, network calls, or other operations that can fail
  • Falling back to a default value when an operation throws
  • Catching rejected promises in async functions with await
  • Running cleanup code in a finally block whether or not an error occurred

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 4, 2026