Is there something along the lines of python 'pass' in javascript?
I want to do the javascript equivalent of:
try:
# Something that throws exception
catch:
pass
Is there something along the lines of python 'pass' in javascript?
I want to do the javascript equivalent of:
try:
# Something that throws exception
catch:
pass
Python doesn't have try/catch. It has try/except. So replacing
catch
withexcept
, we would have this:The empty code block after the catch is equivalent to Python's
pass
.Best Practices
However, one might interpret this question a little differently. Suppose you want to adopt the same semantics as a Python try/except block. Python's exception handling is a little more nuanced, and lets you specify what errors to catch.
In fact, it is considered a best practice to only catch specific error types.
So a best practice version for Python would be, since you want to only catch exceptions you are prepared to handle, and avoid hiding bugs:
You should probably subclass the appropriate error type, standard Javascript doesn't have a very rich exception hierarchy. I chose
TypeError
because it has the same spelling and similar semantics to Python'sTypeError
.To follow the same semantics for this in Javascript, we first have to catch all errors, and so we need control flow that adjusts for that. So we need to determine if the error is not the type of error we want to
pass
with an if condition. The lack of else control flow is what silences theTypeError
. And with this code, in theory, all other types of errors should bubble up to the surface and be fixed, or at least be identified for additional error handling:Comments welcome!
There is, and here it is:
That's right, nothing at all:
pass
is a no-op in Python. You need it for empty blocks becauseis a syntax error. In JavaScript you can just use an empty
catch
block.