Hướng dẫn how do you use multiple exceptions in python? - làm thế nào để bạn sử dụng nhiều ngoại lệ trong python?

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: https://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

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)
4
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
0

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
2

import 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)
4

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
6

Phươ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)
4
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
0

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
2

import 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)
3

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
6

import 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)
7

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)
9

Nhiề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)
4
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
0

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
3
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
4
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
5
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
6

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
2
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
8

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
from 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)
4
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
0

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
3
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
4
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
5
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
6

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
2
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
8

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
from 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.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)
4
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
0

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
3
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
4
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
5
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
6

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
2
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
8

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.

Failed
9as0as1as2

Mã số 4:

Failed
9as0error1as2

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1error4
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
0

import 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: 'miss
1

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:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
2
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)
4
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
0

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
Failed
4
Failed
5
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
4
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
4
Failed
8

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1as4
Failed
5
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
4
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
4 as8

Failed
9
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
13
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
06
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
15as2

Failed
9
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
13
import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
06as1as2

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
2
Failed
2

Failed

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
1
Failed
4
Failed
5
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
4
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
4
Failed
8


Làm thế nào tôi có thể có được nhiều trường hợp ngoại lệ cùng một lúc?

Bắt đầu từ Java 7.0, một khối bắt duy nhất có thể bắt được nhiều trường hợp ngoại lệ bằng cách tách từng loại với | (Biểu tượng ống) trong khối bắt. Bắt nhiều trường hợp ngoại lệ trong một khối bắt duy nhất làm giảm sự trùng lặp mã và tăng hiệu quả.separating each with | (pipe symbol) in the catch block. Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency.

Bạn có thể ném 2 ngoại lệ?

Bạn không thể ném hai ngoại lệ. I E. Bạn không thể làm điều gì đó như: Hãy thử {ném mới bất hợp pháp mới } Catch (bất hợp pháp. I.e. you can't do something like: try { throw new IllegalArgumentException(), new NullPointerException(); } catch (IllegalArgumentException iae) { // ... } catch (NullPointerException npe) { // ... }

Tại sao nó là thực hành tốt nhất để có nhiều ngoại trừ?

Tại sao thực tế tốt nhất là có nhiều câu lệnh ngoại trừ với từng loại lỗi được dán nhãn chính xác?Đảm bảo lỗi được bắt gặp để chương trình sẽ chấm dứt để biết loại lỗi nào đã được ném và.Ensure the error is caught so the program will terminate In order to know what type of error was thrown and the.

Bạn có thể có nhiều điều khoản ngoại trừ cho một lần thử không?

Một câu lệnh thử 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.Trong ví dụ này, chúng tôi có hai điều ngoại trừ., to specify handlers for different exceptions. At most one handler will be executed. In this example, we have two except clauses.