简体   繁体   中英

how to use same multiple exceptions in python

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?


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM