JavaScript Course
JavaScript
/
Beginner

try / catch / finally

Definition

A syntax structure that allows you to execute code that might fail (`try`), gracefully handle the error if it does fail (`catch`), and execute cleanup code regardless of the outcome (`finally`).

Explain Like I'm New

Try: 'Hey JS, try to do this risky thing.' Catch: 'If it explodes, don't crash the whole app, just run this backup plan.' Finally: 'No matter if it exploded or succeeded, clean up your mess.'

Real World Example

Trying to parse a JSON string from LocalStorage. If the string is corrupted, `JSON.parse` will throw an error. Wrapping it in a try/catch prevents the app from white-screening.

Common Use Cases

  • •Handling JSON parsing
  • •Handling API failures in `async/await`
  • •Closing database connections (`finally`)

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What happens if an error occurs inside the `try` block?

intermediate

  • Is the `finally` block mandatory?

advanced

  • Can a `try/catch` block catch errors inside a `setTimeout` callback?

Flash Cards

Question

Is finally mandatory?

Click to reveal answer
Answer

No. You can have just `try/catch`, or just `try/finally` (which runs the cleanup but doesn't suppress the crash). You rarely use `finally` in frontend JS, but it is heavily used in Node.js to close database/file streams.

Question

Can try/catch catch setTimeout errors?

Click to reveal answer
Answer

NO! `try/catch` is completely synchronous. The `try` block finishes instantly, and 1 second later the `setTimeout` callback throws an error. The `catch` block has already finished and packed up its bags. The error will crash the app. You must put the `try/catch` INSIDE the setTimeout callback.