我目前正在开发一个项目,在该项目中,能够演示程序在发生错误时应如何运行至关重要。在这种情况下,我希望我的程序排除失败的 time.localtime()
调用可能产生的任何错误。
据我所知,类似的错误极不可能发生。无论如何,我想涵盖所有可能性。因此,如果我的程序无法从 time.time()
或 time.localtime()
获取响应,会发生什么类型的错误?
try:
time = time.time()
except #nameoferror:
print ("Unable to get current time")
如果时间函数失败,我可以用什么替换“#nameoferror”
以便输出消息?
最佳答案
编辑:我建议您查看 this post/answer也是如此。
这是一个有趣的问题!通常,当您编写 try/except 时,您会捕获如果您预期的错误发生时将引发的异常类型(我认为您已经知道)。
例如:假设我们有变量 var1
,它恰好等于 "hello"
的字符串值。如果您运行 var2 = int(var1))
,Python 将抛出 ValueError
异常。因为您可能会想到这一点,所以您可以编写如下内容:
var1 = "hello"
try:
int(var1)
except ValueError:
print("Invalid casting attempt on non-numeric value.")
就您而言,您正在处理一些不太可能(如果有的话)发生的事情。要处理这样的情况,您可以编写通用的 except
处理。这样,您就不会捕获特定类型的异常。您正在捕获可能因尝试逻辑而引发的任何异常。
示例:
var1 = "hello"
try:
time = time.time()
except:
print("Error occurred during try statement.")
# return value if this is part of a function/handling of your choice
也许其他人会有更好的例子,但是如果我不确定可能抛出什么特定类型,这就是我处理异常的方式。
关于python - 如何处理时间库异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58044096/