Hướng dẫn how do you create a custom error in python? - làm cách nào để tạo lỗi tùy chỉnh trong python?

Python có rất nhiều trường hợp ngoại lệ tích hợp buộc chương trình của bạn phải xuất hiện lỗi khi có điều gì đó trong chương trình.

Tuy nhiên, đôi khi bạn có thể cần tạo các ngoại lệ tùy chỉnh của riêng bạn phục vụ mục đích của bạn.


Tạo các ngoại lệ tùy chỉnh

Trong Python, người dùng có thể xác định các ngoại lệ tùy chỉnh bằng cách tạo một lớp mới. Lớp ngoại lệ này phải được bắt nguồn, trực tiếp hoặc gián tiếp, từ lớp Exception tích hợp. Hầu hết các trường hợp ngoại lệ tích hợp cũng có nguồn gốc từ lớp này.

>>> class CustomError(Exception):
...     pass
...

>>> raise CustomError
Traceback (most recent call last):
...
__main__.CustomError

>>> raise CustomError("An error occurred")
Traceback (most recent call last):
...
__main__.CustomError: An error occurred

Ở đây, chúng tôi đã tạo ra một ngoại lệ do người dùng xác định gọi là CustomError kế thừa từ lớp Exception. Ngoại lệ mới này, giống như các trường hợp ngoại lệ khác, có thể được nêu ra bằng cách sử dụng câu lệnh

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
0 với thông báo lỗi tùy chọn.

Khi chúng tôi đang phát triển một chương trình Python lớn, đó là một thông lệ tốt để đặt tất cả các ngoại lệ do người dùng xác định rằng chương trình của chúng tôi tăng lên trong một tệp riêng biệt. Nhiều mô -đun tiêu chuẩn làm điều này. Họ định nghĩa các ngoại lệ của họ một cách riêng biệt là

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
1 hoặc
# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
2 (nói chung nhưng không phải luôn luôn).

Lớp ngoại lệ do người dùng xác định có thể thực hiện mọi thứ mà một lớp bình thường có thể làm, nhưng chúng tôi thường làm cho chúng đơn giản và súc tích. Hầu hết các triển khai tuyên bố một lớp cơ sở tùy chỉnh và lấy các lớp ngoại lệ khác từ lớp cơ sở này. Khái niệm này được làm rõ hơn trong ví dụ sau.


Ví dụ: Ngoại lệ do người dùng xác định trong Python

Trong ví dụ này, chúng tôi sẽ minh họa cách các trường hợp ngoại lệ do người dùng xác định có thể được sử dụng trong một chương trình để nâng cao và bắt lỗi.

Chương trình này sẽ yêu cầu người dùng nhập một số cho đến khi họ đoán chính xác một số được lưu trữ. Để giúp họ tìm ra nó, một gợi ý được cung cấp cho dù dự đoán của họ lớn hơn hay ít hơn số được lưu trữ.

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")

Dưới đây là một mẫu chạy của chương trình này.

Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.

Chúng tôi đã xác định một lớp cơ sở gọi là

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
3.

Hai trường hợp ngoại lệ khác (

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
4 và
# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
5) thực sự được tăng lên bởi chương trình của chúng tôi có nguồn gốc từ lớp này. Đây là cách tiêu chuẩn để xác định các ngoại lệ do người dùng xác định trong lập trình Python, nhưng bạn không chỉ giới hạn theo cách này.


Tùy chỉnh các lớp ngoại lệ

Chúng tôi có thể tùy chỉnh thêm lớp này để chấp nhận các đối số khác theo nhu cầu của chúng tôi.

Để tìm hiểu về việc tùy chỉnh các lớp ngoại lệ, bạn cần có kiến ​​thức cơ bản về lập trình hướng đối tượng.

Truy cập chương trình theo định hướng đối tượng Python để bắt đầu tìm hiểu về lập trình hướng đối tượng trong Python.

Hãy xem xét một ví dụ:

class SalaryNotInRangeError(Exception):
    """Exception raised for errors in the input salary.

    Attributes:
        salary -- input salary which caused the error
        message -- explanation of the error
    """

    def __init__(self, salary, message="Salary is not in (5000, 15000) range"):
        self.salary = salary
        self.message = message
        super().__init__(self.message)


salary = int(input("Enter salary amount: "))
if not 5000 < salary < 15000:
    raise SalaryNotInRangeError(salary)

Đầu ra

Enter salary amount: 2000
Traceback (most recent call last):
  File "", line 17, in 
    raise SalaryNotInRangeError(salary)
__main__.SalaryNotInRangeError: Salary is not in (5000, 15000) range

Ở đây, chúng tôi đã ghi đè người xây dựng của lớp Exception để chấp nhận các đối số tùy chỉnh của chúng tôi

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
7 và
# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
8. Sau đó, hàm tạo của lớp phụ huynh Exception được gọi thủ công với đối số
Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.
0 bằng cách sử dụng
Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.
1.

Thuộc tính

Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.
2 tùy chỉnh được xác định sẽ được sử dụng sau.

Phương pháp

Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.
3 được kế thừa của lớp Exception sau đó được sử dụng để hiển thị thông báo tương ứng khi
Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.
5 được nêu ra.

Chúng ta cũng có thể tùy chỉnh phương thức

Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.
3 bằng cách ghi đè nó.

class SalaryNotInRangeError(Exception):
    """Exception raised for errors in the input salary.

    Attributes:
        salary -- input salary which caused the error
        message -- explanation of the error
    """

    def __init__(self, salary, message="Salary is not in (5000, 15000) range"):
        self.salary = salary
        self.message = message
        super().__init__(self.message)

    def __str__(self):
        return f'{self.salary} -> {self.message}'


salary = int(input("Enter salary amount: "))
if not 5000 < salary < 15000:
    raise SalaryNotInRangeError(salary)

Đầu ra

Enter salary amount: 2000
Traceback (most recent call last):
  File "/home/bsoyuj/Desktop/Untitled-1.py", line 20, in 
    raise SalaryNotInRangeError(salary)
__main__.SalaryNotInRangeError: 2000 -> Salary is not in (5000, 15000) range

Ở đây, chúng tôi đã ghi đè người xây dựng của lớp Exception để chấp nhận các đối số tùy chỉnh của chúng tôi

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
7 và
# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")
8. Sau đó, hàm tạo của lớp phụ huynh Exception được gọi thủ công với đối số
Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.
0 bằng cách sử dụng
Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.
1.

3 loại lỗi trong Python là gì?

Chủ yếu có ba loại lỗi có thể phân biệt trong Python: lỗi cú pháp, ngoại lệ và lỗi logic.syntax errors, exceptions and logical errors.

Chúng tôi có thể tạo ngoại lệ tùy chỉnh của chúng tôi không?

Trong Java, chúng ta có thể tạo ra các trường hợp ngoại lệ của riêng mình là các lớp có nguồn gốc của lớp ngoại lệ.Tạo ngoại lệ của riêng chúng tôi được gọi là ngoại lệ tùy chỉnh hoặc ngoại lệ do người dùng xác định.Về cơ bản, các ngoại lệ tùy chỉnh Java được sử dụng để tùy chỉnh ngoại lệ theo nhu cầu của người dùng.we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.

Bốn loại lỗi khác nhau trong Python là gì?

NameError được nâng lên khi biến chưa được xác định.MemoryError được nâng lên khi một chương trình hết bộ nhớ.TypeError được nâng lên khi một hàm hoặc hoạt động được áp dụng theo loại không chính xác.Eoferror được nâng lên khi hàm đầu vào () đạt được điều kiện của phần cuối.

Những lỗi nào có thể được nêu ra trong Python?

Lớn lên khi một tuyên bố khẳng định thất bại.Lớn lên khi gán thuộc tính hoặc tham chiếu không thành công.Được nâng lên khi hàm đầu vào () đạt được điều kiện cuối tập tin.Lớn lên khi một hoạt động điểm nổi thất bại.