javascript pass

28,587

Solution 1

pass is a no-op in Python. You need it for empty blocks because

try:
    # Something that throws exception
catch:

# continue other stuff

is a syntax error. In JavaScript you can just use an empty catch block.

try {
    // Something that throws exception
}
catch (e) {}

Solution 2

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 with except, we would have this:

try {
  //     throw any exception
} catch(err) {}  

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:

try:
    raise TypeError
except TypeError as err:
    pass

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's TypeError.

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 the TypeError. 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:

try {                                 // try:
  throw TypeError()                   //     raise ValueError
} catch(err) {                        // # this code block same behavior as
  if (!(err instanceof TypeError)) {  // except ValueError as err:
    throw err                         //     pass
  } 
}                       

Comments welcome!

Share:
28,587
Intra
Author by

Intra

Updated on May 07, 2020

Comments

  • Intra
    Intra almost 4 years

    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
    
  • naught101
    naught101 over 4 years
    eslint complains about this.
  • jameslol
    jameslol almost 3 years
    @naught101 Well yeah, of course it does. Linters are pretty much built to tell us about potentially dangerous things like this. I generally put a comment in the block explaining why I'm not handling the error, which gets rid of the eslint warning. Or you could change rule 'no-empty' to 'off'