110 CHAPTER7. CONTROLSTRUCTURES,PART 1
rarebutpossibleerrors.
Inthecaseofthequadraticsolver, wecheckedthedatabeforethecalltothesqrtfunction.Sometimes
functionsthemselvescheckforpossibleerrorsandreturna specialvaluetoindicatethattheoperationwas
unsuccessful. Forexample,a differentsquarerootoperationmightreturna negative number(say-1)to
indicateanerror. Sincethesquarerootsofrealnumbersarenever negative, thisvaluecouldbeusedtosignal
thatanerrorhadoccurred.Theprogramwouldchecktheresultoftheoperationwitha decision.
discRt = otherSqrt(bb- 4a*c)
if discRt < 0:
print "No realroots."
else:
...
Sometimesprogramsbecomesopepperedwithdecisionstocheckforspecialcasesthatthemainalgo-
rithmforhandlingtherun-of-the-millcasesseemscompletelylost.Programminglanguagedesignershave
comeupwithmechanismsforexceptionhandlingthathelptosolve thisdesignproblem.Theideaofan
exceptionhandlingmechanismis thattheprogrammercanwritecodethatcatchesanddealswitherrorsthat
arisewhentheprogramis running.Ratherthanexplicitlycheckingthateachstepinthealgorithmwassuc-
cessful,a programwithexceptionhandlingcaninessencesay“Dothesesteps,andif any problemcropsup,
handleit thisway.”
We’re notgoingtodiscussallthedetailsofthePythonexceptionhandlingmechanismhere,butI dowant
togive youa concreteexamplesoyoucanseehow exceptionhandlingworksandunderstandprogramsthat
useit.InPython,exceptionhandlingis donewitha specialcontrolstructurethatissimilartoa decision.
Let’s startwitha specificexampleandthentake a lookat thegeneralapproach.
Hereisa versionofthequadraticprogramthatusesPython’s exceptionmechanismtocatchpotential
errorsinthemath.sqrtfunction.
quadratic5.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"
Noticethatthisis basicallytheveryfirstversionofthequadraticprogramwiththeadditionofatry...except
aroundtheheartoftheprogram.Atrystatementhasthegeneralform:
try:
except
WhenPythonencountersatrystatement,it attemptstoexecutethestatementsinsidethebody. If these
statementsexecutewithouterror, controlthenpassestothenextstatementafterthetry...except. If an
erroroccurssomewhereinthebody, Pythonlooksforanexceptclausewitha matchingerrortype.If a
suitableexceptis found,thehandlercodeis executed.
Theoriginalprogramwithouttheexception-handlingproducedthefollowingerror.