Hướng dẫn raise exception and continue python - nâng cao ngoại lệ và tiếp tục python

Đặt cấu trúc

>>> while True print('Hello world')
  File "", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
8 của bạn nhiều hơn. Nếu không, khi bạn gặp lỗi, nó sẽ phá vỡ tất cả các vòng lặp.

Có lẽ sau khi vòng đầu tiên, thêm

>>> while True print('Hello world')
  File "", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
8. Sau đó, nếu một lỗi được nêu ra, nó sẽ tiếp tục với tệp tiếp theo.

for infile in listing:
    try:
        if infile.startswith("ABC"):
            fo = open(infile,"r")
            for line in fo:
                if line.startswith("REVIEW"):
                    print infile
            fo.close()
    except:
        pass

Đây là một ví dụ hoàn hảo về lý do tại sao bạn nên sử dụng câu lệnh

>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
0 ở đây để mở các tệp. Khi bạn mở tệp bằng cách sử dụng
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
1, nhưng lỗi bị bắt, tệp sẽ vẫn mở mãi mãi. Bây giờ là tốt hơn không bao giờ.

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass

Bây giờ nếu một lỗi bị bắt, tệp sẽ bị đóng, vì đó là những gì câu lệnh

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

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 "", 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

>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
3, vì một dấu hai chấm (
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
4) 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 "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
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à

>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
5,
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
6 và
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
7. 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 một gián đoạn do người dùng tạo ra được báo hiệu bằng cách nâng cao ngoại lệ ____38.

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...

Tuyên bố

>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
9 hoạt động như sau.

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

    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "", line 1, in 
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: can only concatenate str (not "int") to str
    
    9 và
    >>> while True:
    ...     try:
    ...         x = int(input("Please enter a number: "))
    ...         break
    ...     except ValueError:
    ...         print("Oops!  That was no valid number.  Try again...")
    ...
    
    1) đượ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

    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "", line 1, in 
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: can only concatenate str (not "int") to str
    
    9 đã hoàn thành.

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

    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "", line 1, in 
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: can only concatenate str (not "int") to str
    
    9, 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
    >>> while True:
    ...     try:
    ...         x = int(input("Please enter a number: "))
    ...         break
    ...     except ValueError:
    ...         print("Oops!  That was no valid number.  Try again...")
    ...
    
    1, 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ó được chuyển sang các câu lệnh

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

>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
9 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
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
9. 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ụ:

... except (RuntimeError, TypeError, NameError):
...     pass

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

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...
1 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ự đó:

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

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

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...
9 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

... except (RuntimeError, TypeError, NameError):
...     pass
0 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
... except (RuntimeError, TypeError, NameError):
...     pass
1 để in tất cả các đối số mà không truy cập rõ ràng
... except (RuntimeError, TypeError, NameError):
...     pass
2.

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

Đầu ra ngoại lệ ____ ____51 đượ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ý.

... except (RuntimeError, TypeError, NameError):
...     pass
4 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ó,
... except (RuntimeError, TypeError, NameError):
...     pass
5, 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
... except (RuntimeError, TypeError, NameError):
...     pass
5 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
... except (RuntimeError, TypeError, NameError):
...     pass
7 được nâng lên bởi
... except (RuntimeError, TypeError, NameError):
...     pass
8 và
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
8 được nâng lên khi người dùng muốn làm gián đoạn chương trình.

... except (RuntimeError, TypeError, NameError):
...     pass
5 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ý

... except (RuntimeError, TypeError, NameError):
...     pass
5 là in hoặc ghi lại ngoại lệ và sau đó đánh lại nó (cho phép người gọi cũng xử lý ngoại lệ):

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error:", err)
except ValueError:
    print("Could not convert data to an integer.")
except Exception as err:
    print(f"Unexpected {err=}, {type(err)=}")
    raise

Tuyên bố

>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
9
>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...
1 có một mệnh đề khác tùy chọn, 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ụ:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

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

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")
4 tốt hơn so với việc thêm mã bổ sung vào mệnh đề
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
9 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
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
9 ____ ____.

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ụ:

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
0

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

Tuyên bố

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")
8 cho phép lập trình viên buộc một ngoại lệ được chỉ định xảy ra. Ví dụ:

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
1

Đối số duy nhất cho

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")
8 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ừ
... except (RuntimeError, TypeError, NameError):
...     pass
4, chẳng hạn như
... except (RuntimeError, TypeError, NameError):
...     pass
5 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ố:

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
2

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

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")
8 cho phép bạn đưa ra ngoại lệ:

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
3

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

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...
1, 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:

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
4

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

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")
8 cho phép mệnh đề
>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
5 tùy chọn:

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
5

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

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
6

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

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
6:

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
7

Để 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

... except (RuntimeError, TypeError, NameError):
...     pass
5, trực tiếp hoặc gián tiếp.Classes for more about Python classes). Exceptions should typically be derived from the
... except (RuntimeError, TypeError, NameError):
...     pass
5 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ố

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

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
8

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

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
9 có mặt, mệnh đề
>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
9 sẽ được thực thi dưới dạng nhiệm vụ cuối cùng trước khi câu lệnh
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
9 hoàn thành. Điều khoản
>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
9 chạy xem câu lệnh
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
9 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 đề

    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "", line 1, in 
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: can only concatenate str (not "int") to str
    
    9, ngoại lệ có thể được xử lý theo mệnh đề
    >>> while True:
    ...     try:
    ...         x = int(input("Please enter a number: "))
    ...         break
    ...     except ValueError:
    ...         print("Oops!  That was no valid number.  Try again...")
    ...
    
    1. Nếu ngoại lệ không được xử lý bởi mệnh đề
    >>> while True:
    ...     try:
    ...         x = int(input("Please enter a number: "))
    ...         break
    ...     except ValueError:
    ...         print("Oops!  That was no valid number.  Try again...")
    ...
    
    1, ngoại lệ sẽ được nêu lại sau khi mệnh đề
    >>> try:
    ...     raise Exception('spam', 'eggs')
    ... except Exception as inst:
    ...     print(type(inst))    # the exception instance
    ...     print(inst.args)     # arguments stored in .args
    ...     print(inst)          # __str__ allows args to be printed directly,
    ...                          # but may be overridden in exception subclasses
    ...     x, y = inst.args     # unpack args
    ...     print('x =', x)
    ...     print('y =', y)
    ...
    
    ('spam', 'eggs')
    ('spam', 'eggs')
    x = spam
    y = eggs
    
    9 đã được thực thi.

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

    >>> while True:
    ...     try:
    ...         x = int(input("Please enter a number: "))
    ...         break
    ...     except ValueError:
    ...         print("Oops!  That was no valid number.  Try again...")
    ...
    
    1 hoặc
    class B(Exception):
        pass
    
    class C(B):
        pass
    
    class D(C):
        pass
    
    for cls in [B, C, D]:
        try:
            raise cls()
        except D:
            print("D")
        except C:
            print("C")
        except B:
            print("B")
    
    4. Một lần nữa, ngoại lệ được nêu lại sau khi mệnh đề
    >>> try:
    ...     raise Exception('spam', 'eggs')
    ... except Exception as inst:
    ...     print(type(inst))    # the exception instance
    ...     print(inst.args)     # arguments stored in .args
    ...     print(inst)          # __str__ allows args to be printed directly,
    ...                          # but may be overridden in exception subclasses
    ...     x, y = inst.args     # unpack args
    ...     print('x =', x)
    ...     print('y =', y)
    ...
    
    ('spam', 'eggs')
    ('spam', 'eggs')
    x = spam
    y = eggs
    
    9 đã được thực thi.

  • Nếu mệnh đề

    >>> try:
    ...     raise Exception('spam', 'eggs')
    ... except Exception as inst:
    ...     print(type(inst))    # the exception instance
    ...     print(inst.args)     # arguments stored in .args
    ...     print(inst)          # __str__ allows args to be printed directly,
    ...                          # but may be overridden in exception subclasses
    ...     x, y = inst.args     # unpack args
    ...     print('x =', x)
    ...     print('y =', y)
    ...
    
    ('spam', 'eggs')
    ('spam', 'eggs')
    x = spam
    y = eggs
    
    9 thực thi câu lệnh
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    2,
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    3 hoặc
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    4, các ngoại lệ không được nêu lại.

  • Nếu câu lệnh

    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "", line 1, in 
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: can only concatenate str (not "int") to str
    
    9 đạt đến câu lệnh
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    2,
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    3 hoặc
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    4, mệnh đề
    >>> try:
    ...     raise Exception('spam', 'eggs')
    ... except Exception as inst:
    ...     print(type(inst))    # the exception instance
    ...     print(inst.args)     # arguments stored in .args
    ...     print(inst)          # __str__ allows args to be printed directly,
    ...                          # but may be overridden in exception subclasses
    ...     x, y = inst.args     # unpack args
    ...     print('x =', x)
    ...     print('y =', y)
    ...
    
    ('spam', 'eggs')
    ('spam', 'eggs')
    x = spam
    y = eggs
    
    9 sẽ thực thi ngay trước khi thực thi câu lệnh
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    2,
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    3 hoặc
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    4.

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

    >>> try:
    ...     raise Exception('spam', 'eggs')
    ... except Exception as inst:
    ...     print(type(inst))    # the exception instance
    ...     print(inst.args)     # arguments stored in .args
    ...     print(inst)          # __str__ allows args to be printed directly,
    ...                          # but may be overridden in exception subclasses
    ...     x, y = inst.args     # unpack args
    ...     print('x =', x)
    ...     print('y =', y)
    ...
    
    ('spam', 'eggs')
    ('spam', 'eggs')
    x = spam
    y = eggs
    
    9 bao gồm một câu lệnh
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except OSError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
    
    4, giá trị được trả về sẽ là một điều khoản từ câu lệnh
    >>> try:
    ...     raise Exception('spam', 'eggs')
    ... except Exception as inst:
    ...     print(type(inst))    # the exception instance
    ...     print(inst.args)     # arguments stored in .args
    ...     print(inst)          # __str__ allows args to be printed directly,
    ...                          # but may be overridden in exception subclasses
    ...     x, y = inst.args     # unpack args
    ...     print('x =', x)
    ...     print('y =', y)
    ...
    
    ('spam', 'eggs')
    ('spam', 'eggs')
    x = spam
    y = eggs
    
    9 ____ ____994, không phải là giá trị từ câu lệnh
    >>> 10 * (1/0)
    Traceback (most recent call last):
      File "", line 1, in 
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: can only concatenate str (not "int") to str
    
    9 ____ ____994.

Ví dụ:

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
9

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

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

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

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
9 được thực thi trong mọi trường hợp.
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str
7 được nâng lên bằng cách chia hai chuỗi không được xử lý bởi mệnh đề
>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...
1 và do đó được tăng lại sau mệnh đề
>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
9 đã được thực thi.

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

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
9 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.

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

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

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
14 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.

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

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.

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
15 đượ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âng cấp 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.

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

Bằng cách sử dụng

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
16 thay vì
>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...
1, 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
for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
16 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.

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

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:

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

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

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass
19 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ệ.

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

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.

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

Làm thế nào để bạn tiếp tục thực hiện sau khi ngoại lệ trong Python?

Nếu một ngoại lệ xảy ra trong quá trình thực hiện mệnh đề thử, 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 ngoại trừ, 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ừ khối.if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.

Tôi có thể sử dụng tiếp tục trong trừ Python không?

Làm thế nào để bạn tiếp tục thử và ngoại trừ trong Python?Tiếp tục xử lý lỗi, hãy thử, ngoại trừ, tiếp tục.Nếu bạn cần xử lý các ngoại lệ trong một vòng lặp, hãy sử dụng câu lệnh tiếp tục để bỏ qua phần còn lại của vòng lặp.In ("Nhưng tôi không quan tâm!use the continue statement to skip the “rest of the loop”. print(" But I don't care!

Làm cách nào để tiếp tục thực hiện sau khi ngoại lệ?

Tiếp tục chương trình khi xảy ra ngoại lệ thời gian đã kiểm tra/biên dịch, bạn có thể tiếp tục chương trình bằng cách xử lý nó bằng cách sử dụng các khối thử.Sử dụng những thứ này, bạn có thể hiển thị thông báo của riêng mình hoặc hiển thị thông báo ngoại lệ sau khi thực hiện chương trình hoàn chỉnh.by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program.

Bạn có thể sử dụng tiếp tục trong ngoại trừ không?

Để tránh điều này, hãy sử dụng câu lệnh tiếp tục trong khối ngoại trừ.Điều này bỏ qua phần còn lại của vòng lặp khi một ngoại lệ xảy ra.use the continue statement in the except block. This skips the rest of the loop when an exception occurs.