Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách catch Python exception trong list comprehension?

Không có built-in function trong Python cho phép handle hoặc ignore exception, nên không possible handle all exceptions trong list comprehension vì list comprehension chứa one hoặc more expressions; chỉ statements có thể catch/ignore/handle exceptions.

Delegating evaluation của exception-prone sub-expressions cho function, là one feasible workaround; others là checks trên values có thể raise exceptions.

Cách chúng ta có thể handle issue này dùng code sau.

Ví dụ

foo = (5, 7, 1, 0, 9)

def bar(self):
    try:
        return [1/i for i in foo]
    except ZeroDivisionError as e:
        print(e)

bar(foo)

Kết quả

integer division or modulo by zero
Process finished with exit code 0