This chapter explains the ES2019 feature “Optional catch binding” by Michael Ficarra.
The proposal allows you to do the following:
That is useful whenever you don’t need the binding (“parameter”) of the
If you never use the variable
catch (). Furthermore, linters that check for unused variables complain in such cases.
There are two general reasons for omitting the
My recommendation is to avoid doing that:
If you can’t and don’t want to avoid it, I suggest encapsulating your code, e.g. inside a function, and to document it well.
Next, we’ll take a look at use cases for omitting
catch bindings and at risks and alternatives.
JSON.parse(), there is one predictable kind of exception – if the input is not legal JSON:
> JSON.parse('abc') SyntaxError: Unexpected token a in JSON at position 0
That’s why it can make sense to use it like this:
There is one problem with this approach: errors in line A that are not related to parsing will be silently ignored. For example, you may make a typo such as
JSON.prase(str). Cases like this have bitten me a few times in the past. Therefore, I now prefer to conditionally re-throw the errors I catch:
When accessing nested properties that may or may not exist, you can avoid checking for their existence if you simply access them and use a default if there is an exception:
I prefer explicit checks. For example:
This code can be shortened if you consider that the
&& operator returns the first falsy operand or the last operand (if there is no falsy operand):
However, this shorter version is also more obscure.
Node.js has the API function
assert.throws(func) that checks whether an error is thrown inside
func. It could be implemented as follows.
This function is an example of wrapping an documenting code that ignores caught exceptions.
The following code snippet demonstrates how to detect whether a given feature exists:
If even logging doesn’t work then, as a last resort, you have no choice but to ignore exceptions (because further logging could make things worse).
Again, we encapsulate and document the slightly unorthodox code.