Bạn có hai tùy chọn [ít nhất].
Sử dụng câu lệnh
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
1:def do_something[parameter]:
if parameter > 100:
# display error message if necessary
return # 'exit' function and return to caller
# rest of the code
Bạn cũng có thể
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
2 chuyển giá trị def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
3 trở lại cho người gọi. Điều này có thể được sử dụng để cung cấp mã trạng thái chẳng hạn [ví dụ: 0: Thành công, 1: Lỗi].Hoặc một cách tiếp cận tốt hơn là
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
4 một ngoại lệ:def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
Xem các trường hợp ngoại lệ trong hướng dẫn Python.
Có các lớp ngoại lệ tích hợp [như
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
5 ở trên]. Bạn cũng có thể xác định của riêng bạn như sau:class ParameterError[Exception]:
pass
Bạn cũng có thể thêm mã bổ sung vào các lớp ngoại lệ tùy chỉnh của mình để xử lý các tham số, hiển thị thông báo lỗi tùy chỉnh, v.v ...
Các trường hợp ngoại lệ tích hợp được liệt kê ở đây.
Nâng cao, trở lại và làm thế nào để không bao giờ thất bại trong Python.
Tôi nghe câu hỏi này rất nhiều: Tôi có nêu ra hoặc trả lại lỗi này trong Python không?
Câu trả lời đúng sẽ phụ thuộc vào các mục tiêu của logic ứng dụng của bạn. Bạn muốn đảm bảo mã Python của bạn không bị thất bại trong âm thầm, cứu bạn và đồng đội của bạn khỏi phải săn lùng các lỗi cố thủ sâu sắc.ensure your Python code doesn’t fail silently, saving you and your teammates from having to hunt down deeply entrenched errors.
Ở đây, sự khác biệt giữa
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
4 và def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
1 khi xử lý các lỗi trong Python.Khi nào nên nâng cao
Tuyên bố
4 cho phép lập trình viên buộc một ngoại lệ cụ thể xảy ra. [8.4 Tăng ngoại lệ]def do_something[parameter]: if parameter > 100: raise ValueError['Parameter should...'] # rest of the code try: do_something[101] except ValueError, e: # display error message if necessary e.g. print str[e]
Sử dụng
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
4 Khi bạn biết bạn muốn có một hành vi cụ thể, chẳng hạn như:raise TypeError["Wanted strawberry, got grape."]
Tăng một ngoại lệ chấm dứt dòng chảy của chương trình của bạn, cho phép ngoại lệ để bong bóng lên ngăn xếp cuộc gọi. Trong ví dụ trên, điều này sẽ cho phép bạn xử lý rõ ràng
class ParameterError[Exception]:
pass
0 sau. Nếu class ParameterError[Exception]:
pass
0 không được xử lý, việc thực thi mã sẽ dừng và bạn sẽ nhận được một thông báo ngoại lệ chưa được xử lý.Nâng cao là hữu ích trong trường hợp bạn muốn xác định một hành vi nhất định sẽ xảy ra. Ví dụ: bạn có thể chọn không cho phép một số từ trong trường văn bản:
if "raisins" in text_field:
raise ValueError["That word is not allowed here"]
Raise có một ví dụ về một ngoại lệ, hoặc một dẫn xuất của lớp ngoại lệ. Dưới đây là tất cả các trường hợp ngoại lệ tích hợp Python.
Nâng cao có thể giúp bạn tránh viết các chức năng thất bại âm thầm. Ví dụ: mã này sẽ không nêu ra một ngoại lệ nếu
class ParameterError[Exception]:
pass
2 không tồn tại:import os
def sandwich_or_bust[bread: str] -> str:
jam = os.getenv["JAM"]
return bread + str[jam] + bread
s = sandwich_or_bust["\U0001F35E"]
print[s]
# Prints "🍞None🍞" which is not very tasty.
Để khiến chức năng
class ParameterError[Exception]:
pass
3 thực sự phá sản, hãy thêm def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
4:import os
def sandwich_or_bust[bread: str] -> str:
jam = os.getenv["JAM"]
if not jam:
raise ValueError["There is no jam. Sad bread."]
return bread + str[jam] + bread
s = sandwich_or_bust["\U0001F35E"]
print[s]
# ValueError: There is no jam. Sad bread.
Bất cứ khi nào mã của bạn tương tác với một biến bên ngoài, mô -đun hoặc dịch vụ, có khả năng thất bại. Bạn có thể sử dụng
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
4 trong một tuyên bố class ParameterError[Exception]:
pass
6 để giúp đảm bảo những thất bại đó không im lặng.Tăng trong class ParameterError[Exception]:
pass
7 và class ParameterError[Exception]:
pass
8
class ParameterError[Exception]:
pass
class ParameterError[Exception]:
pass
Để xử lý một lỗi có thể xảy ra bằng cách thực hiện một hành động nếu có, hãy sử dụng tuyên bố
class ParameterError[Exception]:
pass
7 ____ ____28.try:
s = sandwich_or_bust["\U0001F35E"]
print[s]
except ValueError:
buy_more_jam[]
raise
Điều này cho phép bạn
raise TypeError["Wanted strawberry, got grape."]
1 trước khi tái tạo ngoại lệ. Nếu bạn muốn tuyên truyền một ngoại lệ bị bắt, hãy sử dụng def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
4 mà không có tranh luận để tránh mất dấu vết ngăn xếp.Nếu bạn không biết rằng ngoại lệ sẽ là
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
5, bạn cũng có thể sử dụng raise TypeError["Wanted strawberry, got grape."]
4 hoặc bắt bất kỳ dẫn xuất nào của lớp raise TypeError["Wanted strawberry, got grape."]
5 với raise TypeError["Wanted strawberry, got grape."]
6. Bất cứ khi nào có thể, nó tốt hơn để nâng cao và xử lý các ngoại lệ một cách rõ ràng.Sử dụng
raise TypeError["Wanted strawberry, got grape."]
7 cho mã để thực thi nếu class ParameterError[Exception]:
pass
7 không tăng ngoại lệ. Ví dụ:
try:
s = sandwich_or_bust["\U0001F35E"]
print[s]
except ValueError:
buy_more_jam[]
raise
else:
print["Congratulations on your sandwich."]
Bạn cũng có thể đặt dòng in trong khối
class ParameterError[Exception]:
pass
7, tuy nhiên, điều này ít rõ ràng hơn.Khi nào trở lại
Khi bạn sử dụng
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
1 trong Python, bạn đã trả lại một giá trị. Một chức năng trở về vị trí mà nó được gọi từ.Mặc dù nó thành ngữ nhiều hơn so với các lỗi
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
4 trong Python, nhưng có thể có những lúc bạn tìm thấy def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
1 để được áp dụng nhiều hơn.Ví dụ: nếu mã Python của bạn tương tác với các thành phần khác không xử lý các lớp ngoại lệ, bạn có thể muốn trả lại một tin nhắn thay thế. Ở đây, một ví dụ sử dụng tuyên bố
class ParameterError[Exception]:
pass
7 ____ ____28:from typing import Union
def share_sandwich[sandwich: int] -> Union[float, Exception]:
try:
bad_math = sandwich / 0
return bad_math
except Exception as e:
return e
s = share_sandwich[1]
print[s]
# Prints "division by zero"
Lưu ý rằng khi bạn trả về một đối tượng lớp
raise TypeError["Wanted strawberry, got grape."]
5, bạn sẽ nhận được một đại diện cho giá trị liên quan của nó, thường là mục đầu tiên trong danh sách các đối số của nó. Trong ví dụ trên, đây là lời giải thích chuỗi của ngoại lệ. Trong một số trường hợp, nó có thể là một tuple với thông tin khác về ngoại lệ.Bạn cũng có thể sử dụng
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
1 để đưa ra một đối tượng lỗi cụ thể, chẳng hạn như với if "raisins" in text_field:
raise ValueError["That word is not allowed here"]
7 trong Django. Ví dụ: bạn có thể muốn trả lại if "raisins" in text_field:
raise ValueError["That word is not allowed here"]
8 thay vì if "raisins" in text_field:
raise ValueError["That word is not allowed here"]
9 vì lý do bảo mật:def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
0Sử dụng
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
1 có thể giúp bạn viết mã ồn ào một cách thích hợp khi chức năng của bạn dự kiến sẽ trả lại một giá trị nhất định và khi tương tác với các yếu tố bên ngoài.Phần quan trọng nhất
Thất bại im lặng tạo ra một số lỗi khó chịu nhất để tìm và sửa chữa. Bạn có thể giúp tạo trải nghiệm phát triển dễ chịu cho chính mình và nhóm của bạn bằng cách sử dụng
def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
4 và def do_something[parameter]:
if parameter > 100:
raise ValueError['Parameter should...']
# rest of the code
try:
do_something[101]
except ValueError, e:
# display error message if necessary e.g. print str[e]
1 để đảm bảo rằng các lỗi được xử lý trong mã Python của bạn.ensure that errors are handled in your Python code.Tôi viết về thực tiễn phát triển tốt và cách cải thiện năng suất như một nhà phát triển phần mềm. Bạn có thể nhận được những lời khuyên này ngay trong hộp thư đến của bạn bằng cách đăng ký bên dưới!