Tuning
Tuning

Reputation: 53

User defined exception error using try and except

I am trying to create a user defined exception in the below quadratic roots program (using classes). The intention is to throw and error back if the input list length is not 3 (need 3 inputs for the 3 coefficients). Additionally, I would want the code to stop executing if there is an input error. However, this code isn't working, it doesn't throw an exception and the code continues to execute.

Would greatly appreciate if you could guide me.

class quadRoots():     
def __init__(self,coeff):
    self.A = coeff[0]/coeff[0]
    self.B = coeff[1]/coeff[0]
    self.C = coeff[2]/coeff[0]
    self.Z = 0
    self.R_1 = 0
    self.R_2 = 0
    self.coeff = len(coeff)

    try:
        self.coeff == 3
    except:
        print("Input size is not valid")
    
    
def roots(self):
    import cmath
    self.Z = cmath.sqrt((self.B**2)/4 - (self.C))
    
    self.R_1 = ((-(self.B)/2) + self.Z)
    self.R_2 = ((-(self.B)/2) - self.Z)
    return [self.R_1,self.R_2]

def mult(self):
    return quadRoots.roots(self)[0] * quadRoots.roots(self)[1]

def sumRoots(self):
    return [complex(-(self.B))]

def prodRoots(self):
    return [complex(self.C)]

quadroots([1,-9,14,15]).roots()

Upvotes: 0

Views: 38

Answers (1)

user13854747
user13854747

Reputation:

    try:
        self.coeff == 3
    except:
        print("Input size is not valid")

A Try-Except Chain doesn't work like this. It works when there is an error. But here, there is no error. I suggest you use assert self.coeff == 3, "Input size is not valid". instead, it raises an error, and exits the program, if self.coeff is not equal to 3.

so then the whole try except chain can be replaced by one line. assert self.coeff == 3, "Input size is not valid"

Upvotes: 1

Related Questions