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

Cách raise exception trong except block và catch ở except block sau trong Python?

Chỉ một mệnh đề except duy nhất trong try block được gọi. Nếu bạn muốn exception được catch ở cấp cao hơn, bạn sẽ cần dùng nested try blocks.

Hãy viết 2 try...except blocks như sau:

try:
    try:
        1/0
    except ArithmeticError as e:
        if str(e) == "Zero division":
            print("thumbs up")
        else:
            raise
except Exception as err:
    print("thumbs down")
    raise err

Chúng ta nhận được output sau:

thumbs down
Traceback (most recent call last):
  File "C:/Users/TutorialsPoint1/~.py", line 11, in 
    raise err
  File "C:/Users/TutorialsPoint1/~.py", line 3, in 
    1/0
ZeroDivisionError: division by zero

Theo Python tutorial, có một và chỉ một caught exception per one try statement.