Error Handling: try/catch
Don't let your application crash. Learn how to throw, catch, and safely recover from unexpected errors using try, catch, and finally.
The Safety Net
In JavaScript, when a fatal error occurs (like trying to read a property on undefined), the engine instantly stops executing your script and throws an Exception. If uncaught, this crashes your entire application.
The try...catch statement acts as a safety net. You wrap risky code inside the try block. If an error occurs, the script doesn't crash; instead, execution immediately jumps into the catch block where you can handle it gracefully.
The Finally Block
Often, you need to run cleanup code regardless of whether the operation succeeded or failed (e.g., hiding a loading spinner, or closing a database connection).
The finally block is guaranteed to run after the try and catch blocks finish, no matter what happened.
Throwing Custom Errors
You don't have to wait for JavaScript to throw native errors. You can manually trigger an error state using the throw keyword.
javascript
try {
if (!user.isLoggedIn) {
throw new Error('Authentication failed');
}
showDashboard();
} catch (error) {
console.log(error.message);
} finally {
hideLoader();
}
The Execution Flow
Use the control panel to simulate different network scenarios. Watch closely how the execution path jumps between the try, catch, and finally blocks depending on what happens.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Wrap risky or unpredictable code (like network requests) inside a
tryblock. - If an error occurs, the
tryblock immediately aborts and thecatch(error)block runs. - The
finallyblock runs 100% of the time, regardless of success or failure. - Use the
throwkeyword to manually trigger an error state. - Always throw an
Errorobject (throw new Error()) rather than a raw string so you retain the stack trace.
Done with this concept?
Mark it complete to track your progress. No login needed.