val = int(input('Enter a number:'))
try:
val *= val
except ValueError as e:
raise e
print(val)
### ValueError will be raised if user inputs something other than a number
### this raise e will return the actual error message saying
### ValueError: invalid literal for int() with base 10: 'ok'
在您的情况下,您仍然可以将ValueError保留为要处理的异常,如下所示:
val = int(input('Enter a number:'))
try:
val *= val
except ValueError as e:
raise ACustomException('some debug statement referring to the cause of the error')
print(val)
### now this will raise your exception class besides the ValueError exception, with a debug statement if you choose to have one in it.
try:
with open("foo.json", "rt") as r:
new_count = json.load(r)["count"] + 1
except Exception:
# Is the file missing?
# Is the file there, but not readable?
# Is the file readable, but does not contain valid JSON?
# Is the file format okay, but the data's not a dict with `count`?
# Is the entry `count` there, but is not a number?
print("Something's wrong")
# I don't care. You figure it out.
及
try:
with open("data.json", "rt") as r:
new_count = json.load(r)["count"] + 1
except FileNotFoundError:
print("File is missing.")
except PermissionError:
print("File not readable.")
except json.decoder.JSONDecoderError:
print("File is not valid JSON.")
except KeyError:
print("Cannot find count.")
except TypeError:
print("Count is not a number.")
它有助于确定回溯问题所指的“什么”,以防您可能正在运行的web服务,因此它不是低级错误或通常返回的一般错误,而是将要使用的异常类
更具体地说,举个例子:
在您的情况下,您仍然可以将
ValueError
保留为要处理的异常,如下所示:提出
Exception
就像告诉医生“有什么不对劲”,然后拒绝回答任何问题。比较:及
如果您正在创建一个库,您可以在适当的地方使用预定义的异常类,但有时您需要传达Python创建者从未想到的错误,或者您需要比现有异常做更精细的区分。这是创建自定义异常的时间
例如,Django将定义
django.contrib.auth.models.User.DoesNotExist
异常,以告知代码试图在数据库中查找User
,但找不到与给定条件匹配的User
。能够捕捉django.contrib.auth.models.User.DoesNotExist
就像是一名医生,让一名患者不仅告诉你什么是伤害,还带来X光片和打印的家族史当您使用try-except处理异常时,您将按名称捕获异常,因此使用特定名称有助于您处理异常
例如,如果函数因任何错误而引发
Exception
,则捕获逻辑将变得复杂:另一方面,如果您有子类异常,捕获逻辑很简单:
相关问题 更多 >
编程相关推荐