这是在python中编写异常的正确方法吗?

时间:2019-02-05 14:14:30

标签: python function class exception e

下面的代码是否是用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)   

谢谢!

1 个答案:

答案 0 :(得分:2)

您只是从power返回一个可能要引发异常的字符串。另外,在修改对象之前,应先检查np。 (我不会进一步探讨为什么power设置属性。)

class Calculator:
    def power(self, n, p):
        if n < 0 or p < 0:
            raise ValueError("Both arguments should be non-negative")
        self.n = n
        self.p = p
        return self.n ** self.p

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)