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

วิธี Catch ImportError Exception ใน Python

ImportError raised เมื่อ import module หรือ member ไม่ได้

กรณี 1: Module ไม่มีอยู่

import sys
try:
    from exception import myexception
except Exception as e:
    print(e)
    print(sys.exc_type)

ผลลัพธ์

No module named exception

กรณี 2: Module มีแต่ member ไม่มี

import sys
try:
    from time import datetime
except Exception as e:
    print(e)
    print(sys.exc_type)

ผลลัพธ์

cannot import name datetime