Làm cách nào để bắt được nhiều trường hợp ngoại lệ trong một dòng [trừ khối]
Làm cái này:
try:
may_raise_specific_errors[]:
except [SpecificErrorOne, SpecificErrorTwo] as error:
handle[error] # might log or have some other default behavior...
Các dấu ngoặc đơn được yêu cầu do cú pháp cũ hơn sử dụng dấu phẩy để gán đối tượng lỗi cho tên. Từ khóa as
được sử dụng cho bài tập. Bạn có thể sử dụng bất kỳ tên nào cho đối tượng lỗi, tôi thích cá nhân error
.
Thực hành tốt nhất
Để thực hiện điều này theo cách hiện tại và chuyển tiếp tương thích với Python, bạn cần tách các ngoại lệ bằng dấu phẩy và bọc chúng bằng dấu ngoặc đơn để phân biệt cú pháp trước đó đã gán thể hiện ngoại lệ cho một tên biến bằng cách làm theo loại ngoại lệ để bị bắt với dấu phẩy.
Đây là một ví dụ về cách sử dụng đơn giản:
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
Tôi chỉ chỉ định các ngoại lệ này để tránh ẩn lỗi, mà nếu tôi gặp phải, tôi mong đợi dấu vết ngăn xếp đầy đủ từ.
Điều này được ghi lại ở đây: //docs.python.org/tutorial/errors.html
Bạn có thể gán ngoại lệ cho một biến, [____10 là phổ biến, nhưng bạn có thể thích một biến dài dòng hơn nếu bạn có khả năng xử lý ngoại lệ lâu dài hoặc IDE của bạn chỉ làm nổi bật các lựa chọn lớn hơn thế, như của tôi.] Trường hợp có thuộc tính ARGS. Đây là một ví dụ:
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
Lưu ý rằng trong Python 3, đối tượng
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
1 rơi ra khỏi phạm vi khi khối import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
2 được kết thúc.Phản đối
Bạn có thể thấy mã gán lỗi với dấu phẩy. Việc sử dụng này, biểu mẫu duy nhất có sẵn trong Python 2.5 trở lên, sẽ không được chấp nhận và nếu bạn muốn mã của bạn tương thích về phía trước trong Python 3, bạn nên cập nhật cú pháp để sử dụng biểu mẫu mới:
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError], err: # don't do this in Python 2.6+
print err
print err.args
sys.exit[0]
Nếu bạn thấy gán tên dấu phẩy trong cơ sở mã của mình và bạn đang sử dụng Python 2.5 trở lên, hãy chuyển sang cách thực hiện mới để mã của bạn vẫn tương thích khi bạn nâng cấp.
Trình quản lý bối cảnh import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
3
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
Câu trả lời được chấp nhận thực sự là 4 dòng mã, tối thiểu:
try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
Các dòng
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
4, import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
2, import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
6 có thể được xử lý trong một dòng duy nhất với Trình quản lý ngữ cảnh triệt tiêu, có sẵn trong Python 3.4:from contextlib import suppress
with suppress[IDontLikeYouException, YouAreBeingMeanException]:
do_something[]
Vì vậy, khi bạn muốn
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
6 về một số ngoại lệ nhất định, hãy sử dụng import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
3. Cải thiện bài viết
Lưu bài viết
Đưa ra một đoạn mã có thể ném bất kỳ ngoại lệ nào khác nhau và người ta cần tính đến tất cả các trường hợp ngoại lệ tiềm năng có thể được nêu ra mà không tạo ra mã trùng lặp hoặc các đoạn mã dài, uốn khúc.
Nếu bạn có thể xử lý các ngoại lệ khác nhau bằng cách sử dụng một khối mã, chúng có thể được nhóm lại với nhau thành một tuple như trong mã được đưa ra dưới đây:
Mã số 1:
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
4import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
0import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
2import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
2 import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
4import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
6Phương pháp
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
7 sẽ được gọi nếu có bất kỳ ngoại lệ được liệt kê nào xảy ra. Mặt khác, nếu một trong các trường hợp ngoại lệ phải được xử lý khác nhau, thì hãy đặt nó vào điều khoản ngoại trừ điều khoản như trong mã được đưa ra dưới đây:Mã số 2:
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
4import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
0import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
2import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
2 import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError], err: # don't do this in Python 2.6+
print err
print err.args
sys.exit[0]
3import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
6import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
2 import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError], err: # don't do this in Python 2.6+
print err
print err.args
sys.exit[0]
7import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError], err: # don't do this in Python 2.6+
print err
print err.args
sys.exit[0]
9Nhiều trường hợp ngoại lệ được nhóm thành một hệ thống phân cấp thừa kế. Đối với các trường hợp ngoại lệ như vậy, tất cả các ngoại lệ có thể được bắt gặp bằng cách chỉ định một lớp cơ sở. Ví dụ: thay vì viết mã như trong mã được đưa ra dưới đây -
Mã số 3:
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
4import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
0import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
3try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
4 try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
5try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
6import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
2 try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
8import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1from contextlib import suppress
with suppress[IDontLikeYouException, YouAreBeingMeanException]:
do_something[]
0
Ngoại trừ câu lệnh có thể được viết lại như trong mã được đưa ra dưới đây. Điều này hoạt động bởi vì
from contextlib import suppress
with suppress[IDontLikeYouException, YouAreBeingMeanException]:
do_something[]
1 là một lớp cơ sở mà phổ biến đối với cả ngoại lệ from contextlib import suppress
with suppress[IDontLikeYouException, YouAreBeingMeanException]:
do_something[]
2 và PercissionError.PermissionError exceptions.Mã số 4:
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
4import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
0import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
3try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
4 try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
5try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
6import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
2 try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
8import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1from contextlib import suppress
with suppress[IDontLikeYouException, YouAreBeingMeanException]:
do_something[]
0Ngoại trừ câu lệnh có thể được viết lại như trong mã được đưa ra dưới đây. Điều này hoạt động bởi vì
from contextlib import suppress
with suppress[IDontLikeYouException, YouAreBeingMeanException]:
do_something[]
1 là một lớp cơ sở mà phổ biến đối với cả ngoại lệ from contextlib import suppress
with suppress[IDontLikeYouException, YouAreBeingMeanException]:
do_something[]
2 và PercissionError.se, it is worth noting that
one can get a handle to the thrown exception using them as a keyword as shown in the code given below.Mã số 4:
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
4import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
0import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
3try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
4 try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
5try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
6import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
2 try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
8Ngoại trừ câu lệnh có thể được viết lại như trong mã được đưa ra dưới đây. Điều này hoạt động bởi vì
from contextlib import suppress
with suppress[IDontLikeYouException, YouAreBeingMeanException]:
do_something[]
1 là một lớp cơ sở mà phổ biến đối với cả ngoại lệ from contextlib import suppress
with suppress[IDontLikeYouException, YouAreBeingMeanException]:
do_something[]
2 và PercissionError.Failed9
as
0as
1as
2Mã số 4:
Failed9
as
0error
1as
2import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1error
4import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
0import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
2 Traceback [most recent call last]: File "", line 1, in FileNotFoundError: [Errno 2] No such file or directory: 'miss1
Mặc dù nó không cụ thể để xử lý nhiều trường hợp ngoại lệ mỗi lần, nhưng điều đáng chú ý là người ta có thể có được một điều khiển cho ngoại lệ ném bằng cách sử dụng chúng làm từ khóa như trong mã được đưa ra dưới đây.e variable holds an instance of the raised OSError. This is useful if the exception has to be invested further, such as processing it based on the value of the additional status code. The except clauses are checked in the order listed and the first match executes.
Mã số 5:
2 import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
Failed
2
Traceback [most recent call last]: File "", line 1, in FileNotFoundError: [Errno 2] No such file or directory: 'miss
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
4import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
0import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1Failed4
Failed5
try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
4try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
4 Failed8
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1as
4 Failed5
try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
4try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
4 as
8Failed9
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
13import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
06import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
15as
2‘
Failed9
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
13import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
06as
1as
2
2 import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError]: # the parens are necessary
sys.exit[0]
Failed
2
Failed
import sys
try:
mainstuff[]
except [KeyboardInterrupt, EOFError] as err:
print[err]
print[err.args]
sys.exit[0]
1Failed4
Failed5
try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
4try:
do_something[]
except [IDontLikeYouException, YouAreBeingMeanException] as e:
pass
4 Failed8