0

For example:

try:
    do_a_thing()
except IndexError or ValueError:
    print("There was an error")

I just opened Idle and tried something similar and got:

>>> d = ["1"]
>>> d[2]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    d[2]
IndexError: list index out of range
>>> try:
    print(d[2])
except ValueError or IndexError:
    print("Failed")

    
Traceback (most recent call last):
  File "<pyshell#6>", line 2, in <module>
    print(d[2])
IndexError: list index out of range
>>> 

What Im trying to do is catch two separate errors in one function, not for any specific reason but I'm just curious if something like this is possible. For clarification, I dont want to use two try functions, and I dont want to use:

except Exception as ex:
    print(ex)

because I would still want python to throw an error if something different happened. Is there any easy and straightforward way of doing this or would I have to use a weird roundabout method?

KingTasaz
  • 161
  • 7

1 Answers1

1

The short answer is Yes!

try:
    some_code()
except ValueError:
    do_something_for_velue_error()
except IndexError:
    do_something_for_index_error()

Or treat both equally:

try:
    some_code()
except (ValueError, IndexError):
    do_something_for_both_errors()
Jonatrios
  • 424
  • 2
  • 5