【问题标题】:is this the correct way of writing the exception in python?这是在python中编写异常的正确方法吗?
【发布时间】: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


【解决方案1】:

您只是从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)

【讨论】:

    猜你喜欢
    • 2014-12-17
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    相关资源
    最近更新 更多