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

วิธี Catch StandardError Exception ใน Python

StandardError เป็น base class ของ built-in exceptions หลายตัว (ArithmeticError, AttributeError, AssertionError, etc.)

ตัวอย่าง: AttributeError (subclass ของ StandardError)

import sys

try:
    class Foobar:
        def __init__(self):
            self.p = 0
    
    f = Foobar()
    print(f.p)
    print(f.q)  # AttributeError
except Exception as e:
    print(e)
    print(sys.exc_type)
    print('This is an example of StandardError exception')

ผลลัพธ์

0
Foobar instance has no attribute 'q'

This is an example of StandardError exception