本文介绍了一线异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,可以使用单线以简单,直观的方式设置特殊条件(例如默认值或条件)的值。
In Python, it is possible to use one-liners to set values with special conditions (such as defaults or conditions) in a simple, intuitive way.
result = 0 or "Does not exist." # "Does not exist."
result = "Found user!" if user in user_list else "User not found."
是否可以编写类似的语句来捕获异常?
Is it possible to write a similar statement that catches exceptions?
from json import loads
result = loads('{"value": true}') or "Oh no, explosions occurred!"
# {'value': True}
result = loads(None) or "Oh no, explosions occurred!"
# "Oh no, explosions occurred!" is desired, but a TypeError is raised.
推荐答案
无法执行单行异常python中的-handling语句。可以编写一个函数来执行此操作。
It is not possible to do a one-line exception-handling statement in python. One could write a function to do this.
def safe_execute(default, exception, function, *args):
try:
return function(*args)
except exception:
return default
示例用法:
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
支持多个参数
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.
错误捕获过程可能仍然被中断:
The error-catching process may still be interrupted:
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
如果这种行为是不希望的,请使用 BaseException
:
If this behavior is undesired, use 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!"
这篇关于一线异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!