【发布时间】:2019-06-29 09:15:52
【问题描述】:
下面的代码是用 Python 编写异常的正确方法吗?
class Calculator:
def power(self,n,p):
self.n=n
self.p=p
if self.n>=0 and self.p>=0:
return self.n**self.p
else:
return ("n and p should be non-negative")
myCalculator=Calculator()
T=int(input())
for i in range(T):
n,p = map(int, input().split())
try:
ans=myCalculator.power(n,p)
print(ans)
except Exception as e:
print(e)
【问题讨论】:
-
您是否收到错误消息?代码不起作用吗?你到底想解决什么问题。
-
当
power的任一参数为负时,您可能打算引发异常,而不是返回字符串。 -
引发 ValueError 并排除 ValueError 而不是 Exception。它更专注,不会捕获不同的异常。
-
有时你也可以自定义如果没有现有的异常看起来合适,只需使用
class YourException(Exception): pass定义一个自定义异常 -
如果没有更多上下文,我会允许捕获
Exception而不是更具体的异常,因为至少会记录异常而不是完全忽略异常。
标签: python function class exception