Skip to content

Error Handling

This lesson explains Error Handling in JavaScript with beginner-friendly examples, practical use cases, and clear best practices.

JavaScript Error Handling Overview

JavaScript error handling is the process of detecting, catching, and responding to errors during program execution. Proper error handling prevents applications from crashing unexpectedly and helps developers show meaningful messages, recover safely, and debug problems faster.

JavaScript provides try, catch, finally, throw, and built-in error objects such as Error, TypeError, ReferenceError, and SyntaxError. Error handling is essential for API calls, forms, async/await, promises, user input, JSON parsing, and production applications.

Error Handling Concept Description Common Usage
try Wraps code that may throw an error. Risky code and API logic.
catch Handles an error when one occurs. Show messages and log errors.
finally Runs after try or catch. Cleanup, loading state reset.
throw Creates a custom error. Validation and business rules.
Error Object Represents error details. message, name, stack.
Custom Error User-defined error class. App-specific failures.

JavaScript Error Handling Example

function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }

  return a / b;
}

try {
  const result = divide(10, 0);

  console.log(result);
} catch (error) {
  console.log(error.message);
} finally {
  console.log("Calculation completed");
}

This example uses throw to create a custom error, try to run risky code, catch to handle the error, and finally to run cleanup logic.

Top 10 JavaScript Error Handling Examples

The following examples show common JavaScript error handling patterns used in forms, APIs, JSON parsing, promises, async/await, validation, and production applications.

# Example Syntax
1 Basic try catch try { runTask(); } catch (error) { console.log(error.message); }
2 finally Block try { save(); } catch (error) { log(error); } finally { cleanup(); }
3 Throw Custom Error throw new Error("Invalid input");
4 Validate Required Field if (email === "") { throw new Error("Email is required"); }
5 JSON Parse Error try { JSON.parse(text); } catch (error) { console.log("Invalid JSON"); }
6 Async Await Error try { await fetchUsers(); } catch (error) { showError(); }
7 Fetch Response Error if (!response.ok) { throw new Error("Request failed"); }
8 Promise catch fetchUsers().catch(function(error) { console.log(error.message); });
9 Custom Error Class class AppError extends Error { constructor(message) { super(message); } }
10 Global Error Handler window.addEventListener("error", function(event) { console.log(event.message); });

Best Practices

  • Use try...catch around code that can fail.
  • Use finally for cleanup logic such as hiding loaders.
  • Throw meaningful errors with clear messages.
  • Validate user input before processing it.
  • Check response.ok when using the Fetch API.
  • Handle rejected promises with catch() or try...catch.
  • Show friendly messages to users and detailed logs to developers.
  • Avoid exposing sensitive system details in user-facing error messages.

Common Mistakes

  • Catching errors but doing nothing with them.
  • Showing raw technical error messages to users.
  • Forgetting to handle rejected promises.
  • Using try...catch without fixing or reporting the problem.
  • Not resetting loading states after an error.
  • Throwing strings instead of Error objects.
  • Assuming fetch() throws automatically for HTTP 404 or 500 responses.

Key Takeaways

  • Error handling prevents applications from crashing unexpectedly.
  • try runs code that may fail.
  • catch handles errors safely.
  • finally runs cleanup code after success or failure.
  • throw creates custom errors.
  • Async errors should be handled with try...catch or catch().
  • Good error handling improves user experience and debugging.

Pro Tip

Show simple, helpful error messages to users, but log detailed error information for developers. This improves user experience without exposing sensitive technical details.