Diwakar SHARMA
Diwakar SHARMA

Reputation: 581

Issue with Exception Handling in Python

I am having following issue with my code in propagating an Exception:

What the code should do:

It takes an input for number a of combinations or Test Cases to be run.

It takes n = number and its power = p. (i.e 2^3=8)

If p and n are positive, it needs to print 2^3 = 8 and return it - this is working.

If either n or p is negative, it needs to print "n and p should be non-negative" - this is not working.

My code:

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 

Input given

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

Output received:

243
16
1.0
-1

However, I should have received "n and p should be non-negative" for 3rd and 4th Test Case as last 2 Test Cases(Test Case number 3 and 4) had either of the values set to negative.

What is wrong?

Upvotes: 2

Views: 166

Answers (1)

L3viathan
L3viathan

Reputation: 27273

You're not actually checking the values. Do you want something like that?

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

A NameError doesn't make much sense though, replace it with ValueError.

Upvotes: 1

Related Questions