Ad space (banner)
🟨JavaScript Lessons
Lesson 11 / 69

Error Handling (try...catch)

In this lesson you'll learn error handling with JavaScript's try...catch, so you can keep your program running even when unexpected problems occur. This is for people searching "JavaScript try catch usage" or "JavaScript error handling."

Problems can happen while a program is running (errors can occur). Even if an error occurs inside a try block, you can catch it with a catch (error) { ... } block and prevent the whole program from stopping. It's an insurance-like mechanism: "decide in advance what to do instead, just in case something fails." You can also deliberately trigger an error yourself with throw new Error(message).

The sample code raises an error with throw inside the divide function if you try to divide by zero. Calling divide(10, 0) inside the try block throws the error, and the catch block catches it and displays error.message (the error message). Also important: the rest of the try block is skipped the moment the error occurs.

A common beginner stumbling block is that errors occurring outside the try block can't be caught by catch. Code that might throw an error needs to be properly enclosed in try. Also, catching an error with catch and doing nothing with it (swallowing it silently) should be avoided, since it makes it impossible to figure out the cause of a problem later.

In real development, unpredictable trouble is bound to happen — user input mistakes, network failures, error responses from an external API. Proper error handling is an essential skill for showing users an appropriate message instead of a broken error screen, and for building an app that runs reliably.

Inside a catch block, you can reference not just the error object's .message but also its .name (the error type), letting you respond differently depending on the kind of error. Sorting out ahead of time which kinds of errors you expect lets you write more thoughtful error handling.

To deliberately raise an error, you write something like throw new Error("message"). Besides Error, there are also classes for specific error kinds like TypeError and RangeError, which allow for more detailed error classification.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)