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.

JavaScript6 min readConcept 51 of 63

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.

try {
showSpinner();
const res = await fetchAPI();
if (!res.ok) throw new Error('Invalid Input');
console.log(res.data);
}
catch (err) {
console.error(err.message);
}
finally {
hideSpinner();
}
Execution Log
Waiting for execution...
iThe moment an error is thrown, the try block instantly aborts. The catch block grabs it, and the finally block always runs last to clean up!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens to the remaining code inside a `try` block immediately after an error is thrown?
  2. 2If a `try` block executes successfully without any errors, what happens to the `catch` and `finally` blocks?
  3. 3Why should you throw `new Error('msg')` instead of just throwing a string like `throw 'msg'`?

Remember this

  • Wrap risky or unpredictable code (like network requests) inside a try block.
  • If an error occurs, the try block immediately aborts and the catch(error) block runs.
  • The finally block runs 100% of the time, regardless of success or failure.
  • Use the throw keyword to manually trigger an error state.
  • Always throw an Error object (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.