Không thể thực hiện tuyên bố xử lý ngoại lệ một dòng trong python. Người ta có thể viết một hàm để làm điều này. sử dụng
def safe_execute(default, exception, function, *args):
try:
return function(*args)
except exception:
return default
Ví dụ:
from json import loads
safe_execute("Oh no, explosions occurred!", TypeError, loads, None)
# Returns "Oh no, explosions occurred!"
safe_execute("Huh?", TypeError, int, "10")
#Returns 10
Nhiều đối số được hỗ trợ
from operator import div
safe_execute(
"Divsion by zero is invalid.",
ZeroDivisionError,
div, 1, 0
)
# Returns "Divsion by zero is invalid."
safe_execute(
"Divsion by zero is invalid.",
ZeroDivisionError,
div, 1, 1
)
# Returns 1.
Quá trình lỗi bắt vẫn có thể bị gián đoạn:
from time import sleep
safe_execute(
"Panic!",
Exception,
sleep, 8
)
# Ctrl-c will raise a KeyboardInterrupt
from sys import exit
safe_execute("Failed to exit!", Exception, exit)
# Exits the Python interpreter
Nếu hành vi này là không mong muốn , sử dụng BaseException
:
from time import sleep
safe_execute("interrupted",
BaseException,
sleep, 8)
#Pressing Ctrl-c will return "interrupted"
from sys import exit
safe_execute("Naughty little program!",
BaseException,
exit)
#Returns "Naughty little program!"
Tại sao không đặt tiêu chuẩn 'try..except' vào chức năng? – TigerhawkT3
@Slayer Thật thú vị, Python thực sự sẽ sử dụng một chuỗi (hoặc bất kỳ đối tượng nào khác, trên thực tế) như là một "thay thế" cho 'hoặc'. '0 hoặc" Không tồn tại. "' Sẽ trả về '" Không tồn tại. "'. (Tôi đã thử nghiệm nó.) – 2Cubed
@ TigerhawkT3 Tôi không có quyền truy cập vào nội bộ của hàm 'divide_one_by' - giả sử rằng nó được định nghĩa trong một mô-đun riêng biệt mà tôi đang sử dụng làm phụ thuộc. – 2Cubed