javascript pass

2020-06-06 19:56发布

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

3条回答
老娘就宠你
2楼-- · 2020-06-06 20:32

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!

查看更多
3楼-- · 2020-06-06 20:41

There is, and here it is:


That's right, nothing at all:

try {
    somethingThatThrowsAnException();
} catch (e) {
}
查看更多
不美不萌又怎样
4楼-- · 2020-06-06 20:55

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) {}
查看更多
登录 后发表回答