

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Error Object
incomplete
2: Handling Errors
incomplete
3: Finally
incomplete
4: Throwing Errors
incomplete
5: When to try/catch
incomplete
This lesson's interactive features are locked, please to keep using them
Errors are not something to be scared of. Every program that runs in production handles errors on a constant basis. Our job as developers is to handle the errors gracefully and in a way that aligns with our expectations. Now, I will admit, one of the big criticisms I have of JavaScript is how hard it is to know whether I should expect a function to potentially throw an error or not.
In Go and some other languages, the function signature tells us if we should expect an error:
func getMovieRecord(movieId int) (Movie, error) {
// ...
}This lets us know if we should be prepared to handle an error when we call a function. In JavaScript... we're kinda left guessing. The only way to know for sure is to read the body of the function. This might tempt you to just wrap everything in tons of try/catch blocks, but I'd advise against that.
Here are some rules of thumb for knowing when to use try/catch:
Do you control the input?
If the variable in question is coming from a user, an API, or some other external source, you should probably wrap its initial handling in a try/catch block.
Is the error recoverable?
If the error is something you can recover from, like a network request failing, you should probably wrap it in a try/catch block. If not, let the program crash.
Are you trying to compensate for bad code?
If you wrote some bad code that results in more errors than there need to be, don't wrap it in a try/catch block. Fix the code.
Is it really an abort-worthy error?
In a lot of (especially front-end) JavaScript code, there are so many unknowns that it doesn't make sense to lose control of a program just because a variable is undefined. That's why the optional chaining operator (?.) and nullish coalescing operator (??) were introduced... use them as needed.