0

Suppose I have a code that uses the try and except clause to catch an error in Python as such :

try:
    some_action = print('Please answer my question')

except OSError:
    print("Error occured")
except ValueError:
    print("Error occured")
except BaseException:
    print("Error occured")

Is it possible to combine the except clauses using the OR logical operator in any way, for example in such a way :

try:
   some_action = print('Please answer my question')

except OSError or ValueError or BaseException:
   print ("Error occured")

I tried to look into the Python documentation on the except clauses but I didn't find anything that could help me answer this question.

Perhaps it could be counter-intuitive to allow for OR, for Error handling, as one would prefer to do selective handling of exceptions, but I figured in some instances, using an OR operator could make the code slightly more elegant.

For example using the OR operator in an if/elif statements is possible :

for i in x:
    if A in i:
        pass
    elif B in i:
        pass
    elif C in i:
        pass
    else:
        print ('no A, B, or C in X')

which can be simplified into the following :

for i in x:
    if A in i or B in i or C in i:
       pass
    else:
       print ('no A, B, or C in X') 
N8888
  • 670
  • 2
  • 14
  • 20
  • 1
    Does this answer your question? [Catch multiple exceptions in one line (except block)](https://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block) – shriakhilc Jan 16 '22 at 19:33

1 Answers1

1

From Python Documentation:

An except clause may name multiple exceptions as a parenthesized tuple, for example

    except (OSError, ValueError) as e:
        pass

There is no sense for adding BaseException there, because it's a base class for all exceptions.

Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26