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?