When to Use try/catch

Errors are a natural part of software engineering. Every production application handles errors constantly. Your job is to handle them gracefully.

However, a major challenge in JavaScript is that function signatures do not explicitly declare if they throw errors (unlike languages like Go or Java). The only way to know if a function throws an error is to read its internal code or documentation.

This ambiguity might tempt you to wrap every function call in a try/catch block. Do not do this. It leads to messy, unreadable code.

Here are some rules of thumb for knowing when it is appropriate to use try/catch:

1. Do you control the input?

If a variable is coming from a user, an external API, or a file read, it is untrusted. You should wrap the initial processing of that data in a try/catch because external systems are inherently unpredictable.

2. Is the error recoverable?

If a network request fails, you can recover by showing a retry button to the user. This warrants a try/catch. However, if your application fails to load its core configuration file on startup, there is no recovering—you should let the program crash so the environment can restart it.

3. Are you masking bad code?

If you wrote buggy code that frequently throws TypeErrors, do not wrap it in a try/catch just to silence the errors. Fix the underlying bug.

4. Is it a true failure?

In front-end development especially, it doesn’t make sense to crash the entire UI just because an expected object property is undefined. Instead of using try/catch for simple object lookups, rely on modern features like Optional Chaining (?.) and Nullish Coalescing (??) to handle missing data gracefully.