Skip to main content

What does the try...catch construct do?

General idea

try...catch exists so that code does not "crash" on an error, and instead reacts to it in a controlled way: show a message, retry the action, log it, and so on.


Syntax

javascript
try { // code where an error can occur } catch (error) { // code that runs if an error occurred }

How it works

  1. The code in the try block runs line by line.
  2. If an error occurs inside try, execution of try stops, and control passes to catch.
  3. If there are no errors, the catch block is skipped.
  4. After try...catch, the program keeps running.

Example 1. Without try...catch, the program crashes

javascript
console.log("Start"); JSON.parse("invalid JSON"); // SyntaxError console.log("End"); // does not run

Output:

javascript
Uncaught SyntaxError: Unexpected token i in JSON

Example 2. With try...catch, the program keeps running

javascript
console.log("Start"); try { JSON.parse("invalid JSON"); } catch (err) { console.log("Error caught:", err.message); } console.log("End");

Output:

javascript
Start Error caught: Unexpected token i in JSON at position 0 End

The error is handled, and the program did not crash.


The finally block (optional)

You can add a third block, finally. It always runs, regardless of whether there was an error.

javascript
try { console.log("Running try"); throw new Error("Error!"); } catch (err) { console.log("Caught:", err.message); } finally { console.log("This code runs no matter what"); }

Output:

javascript
Running try Caught: Error! This code runs no matter what

finally is often used for cleaning up resources: closing a connection, stopping a timer, deleting temporary files, and so on.


Can be used with throw

try...catch is often used together with the throw operator to manually throw an exception:

javascript
function divide(a, b) { if (b === 0) throw new Error("Division by zero!"); return a / b; } try { console.log(divide(10, 0)); } catch (e) { console.log("Error:", e.message); }

Behavior details

BehaviorDescription
catch catches only runtime errorsSyntax errors (SyntaxError during code parsing) are not caught
An error inside catch is not caught by the same tryIt needs to be wrapped in a second try...catch
try...catch can be nestedDifferent types of errors can be handled at different levels

Example 3. Nested try...catch

javascript
try { try { throw new TypeError("Wrong type"); } catch (e) { console.log("Inner catch:", e.message); throw new Error("New error"); } } catch (e) { console.log("Outer catch:", e.message); }

Output:

javascript
Inner catch: Wrong type Outer catch: New error

Summary

ElementPurpose
tryCode where an error is possible
catchHandles the error, if one occurred
errorThe variable holding the error object
finallyAlways runs, after try/catch
throwGenerates an exception that catch catches

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.