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')