JavaScript try...catch, throw and Custom Errors
When JavaScript hits something it cannot do, such as reading a property of null, it throws an error object. If nothing catches it, the current script stops and the console shows the error. try...catch lets you catch errors and decide what happens instead.
try, catch, finally
Code that might fail goes in try { }. If anything inside throws, JavaScript skips the rest of the try block and runs catch (err) { }, where err is the thrown value. In the example, parsePrice("twelve") throws, so the line after it never runs. A finally { } block runs either way, which makes it the place for cleanup, such as hiding a loading spinner.
Every built-in error has a name (the type) and a message (the explanation). The common types are:
TypeError: using a value the wrong way, such as callingundefinedor readingnull.length.ReferenceError: using a name that does not exist.SyntaxError: code or JSON that cannot be parsed.RangeError: a number outside the allowed range.
Expected output
12.5 Error: Not a price: "twelve" done checking true ValidationError: email is required
Throwing your own errors
throw new Error("message") signals that a function cannot do its job, such as receiving "twelve" as a price. You can technically throw any value, even a string, but always throw Error objects: they carry a stack trace that shows where the problem started.
For errors your callers may want to handle differently, define a subclass of Error, as ValidationError does. Set this.name so logs show the right type, then check it in catch with err instanceof ValidationError or err.name.
What try...catch cannot catch
try...catch only catches errors thrown while its block is running. A callback scheduled with setTimeout runs later, outside the try. For asynchronous code use the .catch() method of promises, or try...catch around await, both covered in the next two chapters. Syntax errors in the script itself also cannot be caught by the same script, because it never starts running.
Common mistakes
- Empty
catchblocks that silently swallow errors. - Catching errors too early, far from where you can do anything useful.
- Throwing strings:
throw "bad"has no stack trace.
Summary
tryruns code,catchhandles a thrown error,finallyalways runs.- Errors have
nameandmessage; knowTypeError,ReferenceError,SyntaxErrorandRangeError. throw new Error(...), or a subclass, to signal failures.
Quiz: Errors and try...catch