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

User-defined Exceptions ใน Python พร้อมตัวอย่าง


Python โยนข้อผิดพลาดและข้อยกเว็น (exceptions) ทุกครั้งที่โค้ดทำงานผิดปกติ และการทำงานจะหยุดทันที Python ให้เครื่องมือจัดการสถานการณ์เช่นนี้ด้วยวิธีการ exception handling โดยใช้คำสั่ง try-except ข้อยกเว้นมาตรฐานบางอย่างที่พบได้รวมถึง ArithmeticError, AssertionError, AttributeError, ImportError ฯลฯ

การสร้างคลาส User-defined Exception

ที่นี่เราสร้างคลาสข้อยกเว้นใหม่ คือ User_Error Exceptions ต้องสืบทอดมาจากคลาส Exception ในตัว (built-in) โดยตรงหรือโดยอ้อม มาดูตัวอย่างที่กำหนดซึ่งมี constructor และ display method ภายในคลาสที่กำหนด

ตัวอย่าง

# class MyError สืบทอดจาก super class Exception
class User_Error(Exception):
    # Constructor method
    def __init__(self, value):
        self.value = value
    # __str__ display function
    def __str__(self):
        return(repr(self.value))

try:
    raise(User_Error("User defined error"))
    # ค่าของ Exception ถูกเก็บใน error
except User_Error as error:
    print('A New Exception occured:', error.value)

ผลลัพธ์

A New Exception occured: User defined error

การสร้างคลาส User-defined Exception (Multiple Inheritance)

Derived class Exceptions ถูกสร้างเมื่อโมดูลเดียวจัดการข้อผิดพลาดหลายประเภทที่แตกต่างกัน ที่นี่เราสร้าง base class สำหรับ exceptions ที่กำหนดโดยโมดูลนั้น Base class นี้ถูกสืบทอดโดย user-defined class ต่างๆ เพื่อจัดการข้อผิดพลาดประเภทต่างๆ

ตัวอย่าง

# กำหนด Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass

class Dividebyzero(Error):
    """Raised when the input value is zero"""
    pass

try:
    i_num = int(input("Enter a number: "))
    if i_num == 0:
        raise Dividebyzero
except Dividebyzero:
    print("Input value is zero, try again!")
    print()

ผลลัพธ์

Enter a number: Input value is zero, try again!

การสร้างคลาส User-defined Exception (Standard Exceptions)

Runtime error เป็นคลาสในตัวที่ถูกยกขึ้นทุกครั้งที่ข้อผิดพลาดที่เกิดขึ้นไม่ได้อยู่ในหมวดหมู่ที่กล่าวถึง โปรแกรมด้านล่างอธิบายวิธีใช้ runtime error เป็น base class และ user-defined error เป็น derived class

ตัวอย่าง

# User defined error
class Usererror(RuntimeError):
    def __init__(self, arg):
        self.args = arg

try:
    raise Usererror("userError")
except Usererror as e:
    print(e.args)

ผลลัพธ์

('u', 's', 'e', 'r', 'E', 'r', 'r', 'o', 'r')

สรุป

ในบทความนี้ เราได้เรียนรู้วิธีประกาศและนำ user-defined exceptions ไปใช้งานใน Python 3.x หรือเวอร์ชันก่อนหน้า