I am reading from an e-book, here is my code:
import math
class QuadError( Exception ):
pass
def quad(a,b,c):
if a == 0:
ex = QuadError( "Not Quadratic" )
ex.coef = ( a, b, c )
raise ex
if b*b-4*a*c < 0:
ex = QuadError( "No Real Roots" )
ex.coef = ( a, b, c )
raise ex
x1= (-b+math.sqrt(b*b-4*a*c))/(2*a)
x2= (-b-math.sqrt(b*b-4*a*c))/(2*a)
return (x1,x2)
Although I understood the try... except thing inside a function, I can't understand this... I understand what it does, e.g I have used quad(4, 2, 4) that gives me an "No Real Roots" error, or the quad(0, b, c) However I can't understand how the program itself works... So,
if a == 0:
a varibale with the name: "ex", gets the value: QuadError( "Not Quadratic" ) so the programs searches for the Class QuadError that has a pass command in it???! Then why does it print the message??? I would expect something like...
class QuadError( Exception ):
print Exception
Next thing I don't unserstand is the line:
ex.coef = ( a, b, c )
What's that??? is coef a command? Does it do something?
Thanks guys! :)
1 Answer 1
The following is a definition of a class derived from Exception, also known as a subclass of it. The body of it is empty (it adds no new behavior or attributes to the base class), so the statement pass is used because class bodies have to have something in them.
class QuadError(Exception):
pass
In this part of the code:
ex = QuadError( "Not Quadratic" )
ex.coef = ( a, b, c )
raise ex
it's creating an instance of the new class and passing it a string which will become the exception's message attribute and be displayed if the exception is printed. The ex.coef assignment adds an attribute of that name with the value of which is tuple with the coefficients values. This isn't very useful by itself, however other code could try to access the added attribute and use the values somehow. There's no example of doing that in your code however.
In my option it might be better to add the coefficient values to the exceptions message itself so they would be printed along with one.
This is what I mean:
a, b, c = 0, 1, 2
try:
ex = QuadError("Not Quadratic: coefficients a:{} b:{} c:{}".format(a,b,c))
raise ex
except QuadError as qe:
print(qe)
Output:
Not Quadratic: coefficients a:0 b:1 c:2
QuadError(Exception)inherits from Exception, which means that it gets all the fancy goodies that come with the Exception class. Including the ability to act like any standard exception. thepasskeyword is just a control flow statement of sorts that says, no more after me. and ex.coef is being assigned a tuple of a,b,c.ex.coef = ( a, b, c ), you need to go back to basics.