Hướng dẫn how do you print error messages in python? - làm cách nào để in thông báo lỗi trong python?

Người ta có khá nhiều quyền kiểm soát thông tin từ dấu vết sẽ được hiển thị/ghi nhật ký khi bắt các ngoại lệ.

Mật mã

with open("not_existing_file.txt", 'r') as text:
    pass

sẽ tạo ra dấu vết sau:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

In/ghi lại toàn bộ dấu vết

Như những người khác đã đề cập, bạn có thể bắt được toàn bộ dấu vết bằng cách sử dụng mô -đun TraceBack:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()

Điều này sẽ tạo ra đầu ra sau:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

Bạn có thể đạt được điều tương tự bằng cách sử dụng ghi nhật ký:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)

Output:

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

Chỉ in/đăng nhập tên/tin nhắn

Bạn có thể không quan tâm đến toàn bộ TraceBack, nhưng chỉ trong các thông tin quan trọng nhất, chẳng hạn như tên ngoại lệ và thông báo ngoại lệ, sử dụng:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))

Output:

Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'

Cho đến bây giờ các thông báo lỗi thiên đường đã được đề cập nhiều hơn, nhưng nếu bạn đã thử các ví dụ bạn có thể đã thấy một số. Có (ít nhất) hai loại lỗi có thể phân biệt: lỗi cú pháp và ngoại lệ.

8.1. Lỗi cú pháp¶Syntax Errors¶

Lỗi cú pháp, còn được gọi là lỗi phân tích cú pháp, có lẽ là loại khiếu nại phổ biến nhất mà bạn nhận được trong khi bạn vẫn đang học Python:

>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax

Trình phân tích cú pháp lặp lại dòng vi phạm và hiển thị một chút ‘mũi tên chỉ vào điểm sớm nhất trong dòng phát hiện lỗi. Lỗi được gây ra bởi (hoặc ít nhất là được phát hiện AT) mã thông báo trước mũi tên: trong ví dụ, lỗi được phát hiện tại hàm

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
4, vì một dấu hai chấm (
Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
5) bị thiếu trước khi nó. Tên tệp và số dòng được in để bạn biết nơi để xem trong trường hợp đầu vào đến từ một tập lệnh.

8.2. Ngoại lệ haExceptions¶

Ngay cả khi một câu lệnh hoặc biểu thức là chính xác về mặt cú pháp, nó có thể gây ra lỗi khi một nỗ lực được thực hiện để thực hiện nó. Các lỗi được phát hiện trong quá trình thực hiện được gọi là ngoại lệ và không gây tử vong vô điều kiện: bạn sẽ sớm học cách xử lý chúng trong các chương trình Python. Tuy nhiên, hầu hết các trường hợp ngoại lệ không được xử lý bởi các chương trình và dẫn đến các thông báo lỗi như được hiển thị ở đây:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Dòng cuối cùng của thông báo lỗi cho biết những gì đã xảy ra. Các ngoại lệ có các loại khác nhau và loại được in như một phần của thông báo: các loại trong ví dụ là

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
6,
Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
7 và
Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
8. Chuỗi được in dưới dạng loại ngoại lệ là tên của ngoại lệ tích hợp xảy ra. Điều này đúng với tất cả các trường hợp ngoại lệ tích hợp, nhưng không cần phải đúng đối với các ngoại lệ do người dùng xác định (mặc dù đó là một quy ước hữu ích). Tên ngoại lệ tiêu chuẩn là số nhận dạng tích hợp (không dành riêng từ khóa).

Phần còn lại của dòng cung cấp chi tiết dựa trên loại ngoại lệ và nguyên nhân gây ra nó.

Phần trước của thông báo lỗi cho thấy bối cảnh xảy ra ngoại lệ, dưới dạng một dấu vết ngăn xếp. Nói chung, nó chứa một dòng Nguồn liệt kê theo dõi ngăn xếp; Tuy nhiên, nó sẽ không hiển thị các dòng được đọc từ đầu vào tiêu chuẩn.

Các ngoại lệ tích hợp liệt kê các ngoại lệ tích hợp và ý nghĩa của chúng. lists the built-in exceptions and their meanings.

8.3. Xử lý các trường hợp ngoại lệHandling Exceptions¶

Có thể viết các chương trình xử lý các ngoại lệ được chọn. Nhìn vào ví dụ sau, yêu cầu người dùng đầu vào cho đến khi số nguyên hợp lệ đã được nhập, nhưng cho phép người dùng làm gián đoạn chương trình (sử dụng Control-C hoặc bất kỳ hệ điều hành nào hỗ trợ); Lưu ý rằng sự gián đoạn do người dùng tạo ra được báo hiệu bằng cách tăng ngoại lệ

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
9.

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
0

Tuyên bố

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
0 hoạt động như sau.

  • Đầu tiên, mệnh đề thử (câu lệnh giữa các từ khóa

    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    0 và
    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    2) được thực thi.

  • Nếu không xảy ra ngoại lệ, mệnh đề trừ bị bỏ qua và thực thi câu lệnh

    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    0 đã hoàn tất.

  • Nếu một ngoại lệ xảy ra trong quá trình thực hiện mệnh đề

    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    0, phần còn lại của mệnh đề sẽ bị bỏ qua. Sau đó, nếu loại của nó khớp với ngoại lệ được đặt theo tên của từ khóa
    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    2, mệnh đề ngoại trừ được thực thi và sau đó thực thi tiếp tục sau khi khối thử/ngoại trừ.

  • Nếu một ngoại lệ xảy ra không khớp với ngoại lệ có tên trong mệnh đề ngoại trừ, nó sẽ được chuyển sang các câu lệnh

    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    0 bên ngoài; Nếu không tìm thấy người xử lý, đó là một ngoại lệ chưa được xử lý và thực thi sẽ dừng lại với một thông báo như được hiển thị ở trên.

Một câu lệnh

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
0 có thể có nhiều hơn một điều khoản ngoại trừ mệnh đề, để chỉ định trình xử lý cho các ngoại lệ khác nhau. Nhiều nhất một người xử lý sẽ được thực thi. Người xử lý chỉ xử lý các ngoại lệ xảy ra trong mệnh đề thử tương ứng, không phải trong các trình xử lý khác của cùng một câu lệnh
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
0. Một mệnh đề ngoại trừ có thể đặt tên cho nhiều trường hợp ngoại lệ là một bộ phận dấu ngoặc đơn, ví dụ:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
1

Một lớp trong mệnh đề

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
2 tương thích với một ngoại lệ nếu đó là cùng một lớp hoặc một lớp cơ sở của chúng (nhưng không phải là cách khác - một mệnh đề ngoại trừ liệt kê một lớp dẫn xuất không tương thích với một lớp cơ sở). Ví dụ: mã sau sẽ in B, C, D theo thứ tự đó:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
2

Lưu ý rằng nếu các mệnh đề ngoại trừ bị đảo ngược (với

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
0 trước tiên), nó sẽ được in B, B, B - lần khớp đầu tiên ngoại trừ mệnh đề được kích hoạt.

Khi một ngoại lệ xảy ra, nó có thể có các giá trị liên quan, còn được gọi là các đối số ngoại lệ. Sự hiện diện và các loại của các đối số phụ thuộc vào loại ngoại lệ.

Mệnh đề ngoại trừ có thể chỉ định một biến sau tên ngoại lệ. Biến được liên kết với thể hiện ngoại lệ thường có thuộc tính

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
1 lưu trữ các đối số. Để thuận tiện, các loại ngoại lệ tích hợp xác định
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
2 để in tất cả các đối số mà không truy cập rõ ràng
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
3.

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
3

Đầu ra ngoại lệ ____ ____52 được in dưới dạng phần cuối (‘chi tiết) của thông điệp cho các trường hợp ngoại lệ chưa được xử lý.

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
5 là lớp cơ sở chung của tất cả các trường hợp ngoại lệ. Một trong những lớp con của nó,
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
6, là lớp cơ sở của tất cả các trường hợp ngoại lệ không gây tử vong. Các ngoại lệ không phải là các lớp con của
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
6 thường không được xử lý, bởi vì chúng được sử dụng để chỉ ra rằng chương trình nên chấm dứt. Chúng bao gồm
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
8 được nâng lên bởi
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
9 và
Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
9 được nâng lên khi người dùng muốn làm gián đoạn chương trình.

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
6 có thể được sử dụng như một ký tự đại diện bắt (gần như) mọi thứ. Tuy nhiên, đó là thực tế tốt là cụ thể nhất có thể với các loại ngoại lệ mà chúng tôi dự định xử lý và cho phép bất kỳ trường hợp ngoại lệ bất ngờ nào truyền bá.

Mẫu phổ biến nhất để xử lý

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
6 là in hoặc ghi lại ngoại lệ và sau đó nhắc lại nó (cho phép người gọi cũng xử lý ngoại lệ):

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
4

Tuyên bố

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
0
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
2 có một mệnh đề tùy chọn khác, khi có mặt, phải tuân theo tất cả ngoại trừ các điều khoản. Nó rất hữu ích cho mã phải được thực thi nếu mệnh đề thử không tăng ngoại lệ. Ví dụ:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
5

Việc sử dụng mệnh đề

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))
5 tốt hơn so với việc thêm mã bổ sung vào mệnh đề
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
0 vì nó tránh vô tình bắt được một ngoại lệ đã được tăng lên bởi mã được bảo vệ bởi câu lệnh
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
0 ____ ____.

Người xử lý ngoại lệ không chỉ xử lý các trường hợp ngoại lệ xảy ra ngay lập tức trong mệnh đề thử, mà cả những điều xảy ra bên trong các chức năng được gọi (thậm chí gián tiếp) trong mệnh đề thử. Ví dụ:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
6

8.4. Tăng ngoại lệRaising Exceptions¶

Tuyên bố

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))
9 cho phép lập trình viên buộc một ngoại lệ được chỉ định xảy ra. Ví dụ:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
7

Đối số duy nhất cho

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))
9 chỉ ra ngoại lệ được nêu ra. Đây phải là một thể hiện ngoại lệ hoặc một lớp ngoại lệ (một lớp bắt nguồn từ
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
5, chẳng hạn như
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
6 hoặc một trong các lớp con của nó). Nếu một lớp ngoại lệ được thông qua, nó sẽ được khởi tạo ngầm bằng cách gọi hàm tạo của nó mà không có đối số:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
8

Nếu bạn cần xác định xem một ngoại lệ đã được nêu ra nhưng không có ý định xử lý nó, một hình thức đơn giản hơn của câu lệnh

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))
9 cho phép bạn đưa ra ngoại lệ:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
9

8,5. Chuỗi ngoại lệException Chaining¶

Nếu một ngoại lệ chưa được xử lý xảy ra bên trong phần

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
2, nó sẽ có ngoại lệ được xử lý gắn vào nó và được đưa vào thông báo lỗi:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
0

Để chỉ ra rằng một ngoại lệ là hậu quả trực tiếp của một điều khác, câu lệnh

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))
9 cho phép một điều khoản
Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'
6 tùy chọn:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
1

Điều này có thể hữu ích khi bạn đang chuyển đổi các ngoại lệ. Ví dụ:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
2

Nó cũng cho phép vô hiệu hóa chuỗi ngoại lệ tự động bằng thành ngữ

Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'
7:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
3

Để biết thêm thông tin về cơ học chuỗi, hãy xem các ngoại lệ tích hợp.Built-in Exceptions.

8.6. Các trường hợp ngoại lệ do người dùng xác địnhUser-defined Exceptions¶

Các chương trình có thể đặt tên cho các trường hợp ngoại lệ của riêng họ bằng cách tạo một lớp ngoại lệ mới (xem các lớp để biết thêm về các lớp Python). Các ngoại lệ thường nên được lấy từ lớp

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
6, trực tiếp hoặc gián tiếp.Classes for more about Python classes). Exceptions should typically be derived from the
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
6 class, either directly or indirectly.

Các lớp ngoại lệ có thể được xác định làm bất cứ điều gì bất kỳ lớp nào khác có thể làm, nhưng thường được giữ đơn giản, thường chỉ cung cấp một số thuộc tính cho phép thông tin về lỗi được trích xuất bởi người xử lý cho ngoại lệ.

Hầu hết các trường hợp ngoại lệ được xác định với các tên kết thúc trong lỗi Lỗi, tương tự như việc đặt tên cho các ngoại lệ tiêu chuẩn.

Nhiều mô -đun tiêu chuẩn xác định ngoại lệ của chính họ để báo cáo các lỗi có thể xảy ra trong các chức năng mà chúng xác định.

8.7. Xác định các hành động dọn dẹpDefining Clean-up Actions¶

Tuyên bố

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
0 có một mệnh đề tùy chọn khác nhằm xác định các hành động dọn dẹp phải được thực thi trong mọi trường hợp. Ví dụ:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
4

Nếu một mệnh đề

>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
0 có mặt, mệnh đề
>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
0 sẽ được thực thi dưới dạng nhiệm vụ cuối cùng trước khi câu lệnh
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
0 hoàn thành. Điều khoản
>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
0 chạy xem câu lệnh
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
0 có tạo ra một ngoại lệ hay không. Các điểm sau thảo luận về các trường hợp phức tạp hơn khi xảy ra ngoại lệ:

  • Nếu một ngoại lệ xảy ra trong quá trình thực hiện mệnh đề

    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    0, ngoại lệ có thể được xử lý theo mệnh đề
    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    2. Nếu ngoại lệ không được xử lý bởi mệnh đề
    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    2, ngoại lệ sẽ được nêu lại sau khi mệnh đề
    >>> while True print('Hello world')
      File "<stdin>", line 1
        while True print('Hello world')
                       ^
    SyntaxError: invalid syntax
    
    0 đã được thực thi.

  • Một ngoại lệ có thể xảy ra trong quá trình thực hiện mệnh đề

    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    2 hoặc
    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        print("Exception: {}".format(type(exception).__name__))
        print("Exception message: {}".format(exception))
    
    5. Một lần nữa, ngoại lệ được nêu lại sau khi mệnh đề
    >>> while True print('Hello world')
      File "<stdin>", line 1
        while True print('Hello world')
                       ^
    SyntaxError: invalid syntax
    
    0 đã được thực thi.

  • Nếu mệnh đề

    >>> while True print('Hello world')
      File "<stdin>", line 1
        while True print('Hello world')
                       ^
    SyntaxError: invalid syntax
    
    0 thực thi câu lệnh
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    3,
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    4 hoặc
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    5, các ngoại lệ không được nêu lại.

  • Nếu câu lệnh

    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    0 đạt đến câu lệnh
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    3,
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    4 hoặc
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    5, mệnh đề
    >>> while True print('Hello world')
      File "<stdin>", line 1
        while True print('Hello world')
                       ^
    SyntaxError: invalid syntax
    
    0 sẽ thực thi ngay trước khi thực thi câu lệnh
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    3,
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    4 hoặc
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    5.

  • Nếu một điều khoản

    >>> while True print('Hello world')
      File "<stdin>", line 1
        while True print('Hello world')
                       ^
    SyntaxError: invalid syntax
    
    0 bao gồm một câu lệnh
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
    
    5, giá trị được trả về sẽ là định đề từ câu lệnh
    >>> while True print('Hello world')
      File "<stdin>", line 1
        while True print('Hello world')
                       ^
    SyntaxError: invalid syntax
    
    0 ____ ____995, không phải là giá trị từ câu lệnh
    try:
        with open("not_existing_file.txt", 'r') as text:
            pass
    except Exception as exception:
        logger.error(exception, exc_info=True)
    
    0 ____ ____95.

Ví dụ:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
5

Một ví dụ phức tạp hơn:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
6

Như bạn có thể thấy, mệnh đề

>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
0 được thực thi trong mọi sự kiện.
Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
8 được nâng lên bằng cách chia hai chuỗi không được xử lý bởi mệnh đề
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
2 và do đó được tăng lại sau khi mệnh đề
>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
0 đã được thực thi.

Trong các ứng dụng trong thế giới thực, mệnh đề

>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
0 rất hữu ích để phát hành các tài nguyên bên ngoài (như tệp hoặc kết nối mạng), bất kể việc sử dụng tài nguyên có thành công hay không.

8.8. Hành động dọn dẹp được xác định trướcPredefined Clean-up Actions¶

Một số đối tượng xác định các hành động làm sạch tiêu chuẩn sẽ được thực hiện khi đối tượng không còn cần thiết, bất kể hoạt động sử dụng đối tượng thành công hay không. Nhìn vào ví dụ sau, cố gắng mở một tệp và in nội dung của nó lên màn hình.

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
7

Vấn đề với mã này là nó để tệp mở trong một khoảng thời gian không xác định sau khi phần này của mã đã hoàn tất việc thực thi. Đây không phải là một vấn đề trong các tập lệnh đơn giản, nhưng có thể là một vấn đề cho các ứng dụng lớn hơn. Câu lệnh

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
15 cho phép các đối tượng như các tệp được sử dụng theo cách đảm bảo chúng luôn được dọn sạch kịp thời và chính xác.

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
8

Sau khi câu lệnh được thực thi, tệp F luôn được đóng, ngay cả khi gặp sự cố trong khi xử lý các dòng. Các đối tượng, giống như các tệp, cung cấp các hành động làm sạch được xác định trước sẽ chỉ ra điều này trong tài liệu của họ.

8,9. Tăng và xử lý nhiều trường hợp ngoại lệ không liên quanRaising and Handling Multiple Unrelated Exceptions¶

Có những tình huống cần phải báo cáo một số ngoại lệ đã xảy ra. Đây thường là trường hợp trong các khung đồng thời, khi một số nhiệm vụ có thể thất bại song song, nhưng cũng có những trường hợp sử dụng khác trong đó mong muốn tiếp tục thực thi và thu thập nhiều lỗi thay vì tăng ngoại lệ đầu tiên.

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
16 được xây dựng kết thúc một danh sách các trường hợp ngoại lệ để chúng có thể được nêu cùng nhau. Đó là một ngoại lệ, vì vậy nó có thể bị bắt như bất kỳ ngoại lệ nào khác.

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()
9

Bằng cách sử dụng

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
17 thay vì
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)
2, chúng ta chỉ có thể xử lý chọn lọc các ngoại lệ trong nhóm phù hợp với một loại nhất định. Trong ví dụ sau, hiển thị một nhóm ngoại lệ lồng nhau, mỗi điều khoản
Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
17 trích xuất từ ​​các ngoại lệ của nhóm thuộc một loại nhất định trong khi cho phép tất cả các trường hợp ngoại lệ khác tuyên truyền đến các mệnh đề khác và cuối cùng sẽ được đọc lại.

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
0

Lưu ý rằng các ngoại lệ lồng nhau trong một nhóm ngoại lệ phải là trường hợp, không phải loại. Điều này là do trong thực tế, các trường hợp ngoại lệ thường sẽ là những trường hợp đã được chương trình nâng lên và bắt gặp, theo mô hình sau:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
1

8.10. Làm phong phú các ngoại lệ với Ghi chú JoEnriching Exceptions with Notes¶

Khi một ngoại lệ được tạo ra để được nâng lên, nó thường được khởi tạo với thông tin mô tả lỗi đã xảy ra. Có những trường hợp hữu ích để thêm thông tin sau khi ngoại lệ bị bắt. Với mục đích này, các ngoại lệ có một phương thức

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
20 chấp nhận một chuỗi và thêm nó vào danh sách ghi chú ngoại lệ. Kết xuất theo dõi tiêu chuẩn bao gồm tất cả các ghi chú, theo thứ tự chúng được thêm vào, sau ngoại lệ.

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
2

Ví dụ: khi thu thập các ngoại lệ thành một nhóm ngoại lệ, chúng tôi có thể muốn thêm thông tin ngữ cảnh cho các lỗi riêng lẻ. Trong các ngoại lệ sau đây trong nhóm có một ghi chú cho biết khi nào lỗi này đã xảy ra.

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
3

Làm cách nào để in một tin nhắn ngoại lệ?

Sử dụng phương thức printStackTrace () - nó in tên của ngoại lệ, mô tả và dấu vết ngăn xếp hoàn chỉnh bao gồm dòng xảy ra ngoại lệ. Sử dụng phương thức toString () - nó in tên và mô tả ngoại lệ. Sử dụng phương thức getMessage () - chủ yếu được sử dụng. Nó in mô tả về ngoại lệ. − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.

Làm thế nào để bạn đọc một thông báo lỗi trong Python?

Trong Python, tốt nhất là đọc dấu vết từ dưới lên:..
Hộp màu xanh: Dòng cuối cùng của dấu vết là dòng thông báo lỗi.....
Hộp màu xanh lá cây: Sau tên ngoại lệ là thông báo lỗi.....
Hộp màu vàng: Tiếp tục lên dấu vết là các cuộc gọi chức năng khác nhau di chuyển từ dưới lên trên, gần đây nhất đến gần đây nhất ..

Làm thế nào để bạn tìm thấy mã lỗi trong Python?

Bất cứ khi nào xảy ra lỗi thời gian chạy, Python tạo ra một đối tượng ngoại lệ.Sau đó, nó tạo ra và in một dấu vết của lỗi đó với chi tiết về lý do tại sao lỗi xảy ra.Dưới đây là những ngoại lệ phổ biến trong Python: indexError - bạn sẽ gặp lỗi này khi không tìm thấy chỉ mục trong một chuỗi.Python creates an exception object. It then creates and prints a traceback of that error with details on why the error happened. Here are common exceptions in Python: IndexError – You will get this error when an index is not found in a sequence.