Skip to main content
 首页 » 编程设计

python之Python 中的异常处理问题

2025年04月02日14www_RR

我的代码在传播异常时遇到以下问题:

代码应该做什么:

它需要一个输入来运行 a 个组合或测试用例。

它需要 n = 数字,它的幂 = p。 (即 2^3=8)

如果 p 和 n 是正数,它需要打印 2^3 = 8 并返回它 - 这是可行的。

如果 n 或 p 是负数,它需要打印“n and p should be non-negative”——这是行不通的。

我的代码:

class Calculator(): 
    def power(self,n,p): 
        self.n=n 
        self.p=p 
        try: 
            raise NameError("n and p should be non-negative") 
 
        except NameError: 
            a=pow(n,p) 
            return a 
myCalculator=Calculator() 
T=int(raw_input()) 
for i in range(T): 
    n,p = map(int, raw_input().split()) 
    try: 
        ans=myCalculator.power(n,p) 
        print ans 
    except Exception,e: 
        print e  

给定的输入

4 
3 5 
2 4 
-1 -2 
-1 3 

收到的输出:

243 
16 
1.0 
-1 

但是,对于第 3 个和第 4 个测试用例,我应该收到“n 和 p 应该是非负数”,因为最后 2 个测试用例(测试用例编号 3 和 4)中的任何一个值都设置为负数。

怎么了?

请您参考如下方法:

您实际上并没有检查这些值。你想要这样的东西吗?

class Calculator(): 
    def power(self,n,p): 
        self.n=n 
        self.p=p 
        if n<0 or p<0: 
            raise NameError("n and p should be non-negative") 
        a=pow(n,p) 
        return a 

虽然 NameError 没有多大意义,但将其替换为 ValueError。