Error Handling

Sometimes code fails — a value is missing, an argument is the wrong type, a request breaks. Error handling lets you catch that failure and decide what happens next, instead of letting it stop everything after it.

What happens without a try/catch

Try running this — the second console.log throws, and notice the third one never even runs:

Try it yourself
Console output

An uncaught error stops the script right where it happened. Everything written after it in the same block simply never executes.

try, catch, and finally

Wrapping risky code in try lets you catch the error instead of letting it stop everything. finally runs either way — whether an error happened or not — which makes it useful for cleanup:

Try it yourself
Console output

As soon as the error is thrown inside try, JavaScript jumps straight to catch — the rest of the try block is skipped, but the program itself keeps going afterward.

Throwing your own errors

throw lets you raise an error on purpose, with a message that actually explains what went wrong — rather than waiting for JavaScript's own, often vaguer, error to show up later:

Try it yourself
Console output

Custom error types

For bigger projects, it's common to create your own error type by extending Error. That way, a catch block can tell different kinds of failures apart by name, instead of every error looking the same:

Try it yourself
Console output
Note: a try/catch only catches errors that happen while the code inside try is actively running. Code that runs later — after a timer finishes, or a network response comes back — needs its own way of handling failure, which is exactly what promises, in the next lesson, are built for.