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

Cách capture và print Python exception message?

Python exception messages có thể được capture và printed theo nhiều cách như hai ví dụ code dưới. Trong cái đầu, chúng ta dùng attribute message của exception object.

Ví dụ

try:
    a = 7/0
    print(float(a))
except BaseException as e:
    print(e.message)

Kết quả

integer division or modulo by zero

Trong trường hợp code cho trước, chúng ta import module sys và dùng attribute sys.exc_value để capture và print exception message.

Ví dụ

import sys

def catchEverything():
    try:
        a = 'sequel'
        b = 0.8
        print(a + b)
    except Exception as e:
        print(sys.exc_value)

catchEverything()

Kết quả

cannot concatenate 'str' and 'float' objects