Lý do cho sự cố gắng cố gắng-else tồn tại là gì?
Khối try
cho phép bạn xử lý lỗi dự kiến. Khối except
chỉ nên nắm bắt các ngoại lệ mà bạn đã chuẩn bị để xử lý. Nếu bạn xử lý một lỗi không mong muốn, mã của bạn có thể làm sai và ẩn lỗi.
Một điều khoản
no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
0 sẽ thực thi nếu không có lỗi và bằng cách không thực thi mã đó trong khối try
, bạn tránh bị lỗi bất ngờ. Một lần nữa, việc bắt một lỗi bất ngờ có thể ẩn lỗi.Thí dụ
Ví dụ:
try:
try_this[whatever]
except SomeException as the_exception:
handle[the_exception]
else:
return something
Bộ "thử, ngoại trừ" có hai mệnh đề tùy chọn,
no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
0 và no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
3. Vì vậy, nó thực sự là no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
4.no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
0 sẽ chỉ đánh giá nếu không có ngoại lệ từ khối try
. Nó cho phép chúng tôi đơn giản hóa mã phức tạp hơn bên dưới:no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
Vì vậy, nếu chúng ta so sánh ____10 với giải pháp thay thế [có thể tạo ra lỗi], chúng ta sẽ thấy rằng nó sẽ giảm các dòng mã và chúng ta có thể có cơ sở mã dễ đọc hơn, có thể duy trì và ít lỗi hơn.
no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
3
no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
3 sẽ thực thi bất kể điều gì, ngay cả khi một dòng khác đang được đánh giá với câu lệnh trả lại.Bị phá vỡ với mã giả
Nó có thể giúp phá vỡ điều này, trong hình thức nhỏ nhất có thể thể hiện tất cả các tính năng, với các bình luận. Giả sử chính xác cú pháp này [nhưng không thể chạy được trừ khi các tên được xác định] mã giả là trong một hàm.
Ví dụ:
try:
try_this[whatever]
except SomeException as the_exception:
handle_SomeException[the_exception]
# Handle a instance of SomeException or a subclass of it.
except Exception as the_exception:
generic_handle[the_exception]
# Handle any other exception that inherits from Exception
# - doesn't include GeneratorExit, KeyboardInterrupt, SystemExit
# Avoid bare `except:`
else: # there was no exception whatsoever
return something[]
# if no exception, the "something[]" gets evaluated,
# but the return will not be executed due to the return in the
# finally block below.
finally:
# this block will execute no matter what, even if no exception,
# after "something" is eval'd but before that value is returned
# but even if there is an exception.
# a return here will hijack the return functionality. e.g.:
return True # hijacks the return in the else clause above
Bộ "thử, ngoại trừ" có hai mệnh đề tùy chọn,
no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
0 và no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
3. Vì vậy, nó thực sự là no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
4.no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
0 sẽ chỉ đánh giá nếu không có ngoại lệ từ khối try
. Nó cho phép chúng tôi đơn giản hóa mã phức tạp hơn bên dưới:Vì vậy, nếu chúng ta so sánh ____10 với giải pháp thay thế [có thể tạo ra lỗi], chúng ta sẽ thấy rằng nó sẽ giảm các dòng mã và chúng ta có thể có cơ sở mã dễ đọc hơn, có thể duy trì và ít lỗi hơn.
no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
3 sẽ thực thi bất kể điều gì, ngay cả khi một dòng khác đang được đánh giá với câu lệnh trả lại.Bị phá vỡ với mã giả
$ python -m pydoc exceptions
Nó có thể giúp phá vỡ điều này, trong hình thức nhỏ nhất có thể thể hiện tất cả các tính năng, với các bình luận. Giả sử chính xác cú pháp này [nhưng không thể chạy được trừ khi các tên được xác định] mã giả là trong một hàm.
$ python -m pydoc builtins
Đúng là chúng ta có thể đưa mã vào khối
no_error = None
try:
try_this[whatever]
no_error = True
except SomeException as the_exception:
handle[the_exception]
if no_error:
return something
0 trong khối try
thay vào đó, nơi nó sẽ chạy nếu không có ngoại lệ, nhưng nếu mã đó làm tăng ngoại lệ của loại chúng ta đang bắt? Để nó trong khối try
sẽ che giấu lỗi đó.BaseException
Exception
ArithmeticError
FloatingPointError
OverflowError
ZeroDivisionError
AssertionError
AttributeError
BufferError
EOFError
ImportError
ModuleNotFoundError
LookupError
IndexError
KeyError
MemoryError
NameError
UnboundLocalError
OSError
BlockingIOError
ChildProcessError
ConnectionError
BrokenPipeError
ConnectionAbortedError
ConnectionRefusedError
ConnectionResetError
FileExistsError
FileNotFoundError
InterruptedError
IsADirectoryError
NotADirectoryError
PermissionError
ProcessLookupError
TimeoutError
ReferenceError
RuntimeError
NotImplementedError
RecursionError
StopAsyncIteration
StopIteration
SyntaxError
IndentationError
TabError
SystemError
TypeError
ValueError
UnicodeError
UnicodeDecodeError
UnicodeEncodeError
UnicodeTranslateError
Warning
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWarning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
GeneratorExit
KeyboardInterrupt
SystemExit
Chúng tôi muốn giảm thiểu các dòng mã trong khối try
để tránh các trường hợp ngoại lệ mà chúng tôi không mong đợi, theo nguyên tắc nếu mã của chúng tôi thất bại, chúng tôi muốn nó thất bại lớn. Đây là một thực hành tốt nhất.
Tôi hiểu rằng ngoại lệ không phải là lỗi
Trong Python, hầu hết các trường hợp ngoại lệ là lỗi.
try:
try_this[whatever]
except SomeException as the_exception:
handle[the_exception]
raise
Chúng ta có thể xem hệ thống phân cấp ngoại lệ bằng cách sử dụng PYDOC. Ví dụ, trong Python 2:
try:
try_this[whatever]
except SomeException as the_exception:
handle[the_exception]
raise DifferentException from the_exception
hoặc Python 3: