7.4.EXCEPTIONHANDLING 111
Traceback (innermostlast):
File "
File "quadratic.py",line 13, in?
discRoot = math.sqrt(b b - 4 a * c)
OverflowError: mathrange error
Thelastlineofthiserrormessageindicatesthetypeoferrorthatwasgenerated,namelyanOverflowError.
TheupdatedversionoftheprogramprovidesanexceptclausetocatchtheOverflowError.
Hereis theerrorhandlingversioninaction:
This program findsthe real solutions to a quadratic
Please enter the coefficients(a, b, c): 1,2,3
No real roots
Insteadofcrashing,theexceptionhandlercatchestheerrorandprintsa messageindicatingthattheequation
doesnothave realroots.
Thenicethingaboutthetry...exceptstatementis thatit canbeusedto catchany kindoferror, even
onesthatmightbedifficulttotestfor, andhopefully, providea gracefulexit.Forexample,inthequadratic
solver, therearelotsofotherthingsthatcouldgowrongbesideshavinga badsetofcoefficients.If theuser
failstotypethecorrectnumberofinputs,theprogramgeneratesaValueError. Iftheuseraccidently
typesanidentifierinsteadofa number, theprogramgeneratesaNameError. If theusertypesina valid
Pythonexpressionthatproducesnon-numericresults,theprogramgeneratesaTypeError. A singletry
statementcanhave multipleexceptclausestocatchvariouspossibleclassesoferrors.
Here’s onelastversionoftheprogramdesignedtorobustlyhandleany possibleerrorsintheinput.
quadratic6.py
import math
def main():
print "This programfinds the real solutions to a quadratic\n"
try:
a, b, c = input("Please enter the coefficients (a, b, c):")
discRoot = math.sqrt(b* b - 4 * a * c)
root1 = (-b + discRoot)/ (2 * a)
root2 = (-b - discRoot)/ (2 * a)
print "\nThesolutions are:", root1, root2
except OverflowError:
print "\nNoreal roots"
except ValueError:
print "\nYoudidn’t give me three coefficients."
except NameError:
print "\nYoudidn’t enter three numbers"
except TypeError:
print "\nYourinputs were not all numbers"
except:
print "\nSomethingwent wrong, sorry!"
Themultipleexcepts aresimilartoelifs. Ifanerroroccurs,Pythonwilltryeachexceptinturn
lookingforonethatmatchesthetypeoferror. Thebareexceptatthebottomactslike anelseandwill
beusedif noneoftheothersmatch.If thereis nodefaultat thebottomandnoneoftheexcepttypesmatch
theerror, thentheprogramcrashesandPythonreportstheerror.
Youcanseehow thetry...exceptstatementallowsusto writereallybullet-proofprograms.Whether
youneedtogotothismuchtroubledependsonthetypeofprogramthatyouarewriting.Inyourbeginning