Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Capture และ Print Python Exception Message

1. ใช้ attribute .message (Python 2)

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

ผลลัพธ์

integer division or modulo by zero

2. ใช้ sys.exc_value (Python 2)

import sys

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

catchEverything()

ผลลัพธ์

cannot concatenate 'str' and 'float' objects

Python 3: ใช้ str(e) หรือ e.args[0]