Error Handling
EasyIn plain terms
When something goes wrong—invalid input, a failed network request, a bug—JavaScript "throws" an error. If you do not catch it, the error can crash your app or show an ugly message to the user.
Wrap risky code in a try block. If an error occurs, execution jumps to the catch block, where you receive the error object and can log it, show a message, or recover. The finally block runs no matter what—use it for cleanup like closing connections. You can also throw your own errors with throw new Error("message") when you detect invalid state.
What you need to know
- •try, catch, finally
- •throw
- •Error object with message
Try it yourself
Copy the code below and run it in your browser console or a code editor:
try {
const data = JSON.parse(invalidJson);
} catch (err) {
console.error('Parse error:', err.message);
} finally {
cleanup();
}
throw new Error('Something went wrong');Why this matters
Robust apps handle errors explicitly. Interviewers ask how you handle async errors (try/catch with await), when to rethrow, and how you structure error handling in APIs.
How it connects
Use try/catch with async/await for Promise rejections. Custom errors (extend Error) improve clarity. finally is for cleanup. Unhandled rejections can crash the app—always catch or use global handler.
Interview focus
Be ready to explain these; they come up often in JS interviews.
- ▸try/catch/finally: catch receives error; finally runs always. Use for cleanup.
- ▸throw new Error("msg"); custom errors by extending Error.
- ▸Async: await in try/catch; unhandled rejection = crash or global handler.
Learn more
Dive deeper with these trusted resources: