0
votes
a=[1,2,3]
try:
    print(a[6])
except IndexError:
    print(a[7])
except IndexError:
    print(a[1])

Traceback (most recent call last):
File "", line 2, in
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "", line 4, in
IndexError: list index out of range

so, I have to use a not graceful way:

a=[1,2,3]
try:
    print(a[6])
except IndexError:
    try:
        print(a[7])
    except IndexError:
        print(a[1])

Is there any good approach to write the code?


1
Multiple except blocks on a try are used to catch multiple exception types that could happen in the try, not exceptions happening in except blocks. - user2357112 supports Monica
In addition (this is beyond what you're asking) but you can catch different types of exceptions like this except (IndexError, ValueError) as e - nico

1 Answers

2
votes

Use can wrap your try: ... except:... with for loop:

a = [1,2,3]
for i in [6,7,1]:
    try:
        print(a[i])
    except IndexError:
        pass
# 2