5. General idea
4 general steps:
1. Keep watch on a particular section of code
2. If we get an exception, raise/throw that
exception (let it be known)
3. Look for a catcher that can handle that kind
of exception
4. If found, handle it, otherwise let Python
handle it (which usually halts the program)
Module 12 : Exceptions 5
8. Try suite
• The try suite contains code that we want to
monitor for errors during its execution.
• If an error occurs anywhere in that try suite,
Python looks for a handler that can deal with
the error.
• If no special handler exists, Python handles it,
meaning the program halts and with an error
message as we have seen so many times
Module 12 : Exceptions
try:
Code to run
8
9. Except suite
• An except suite (perhaps multiple
except suites) is associated with a try
suite.
• Each exception names a type of exception it is
monitoring for (can handle).
• If the error that occurs in the try suite
matches the type of exception, then that
except suite is activated.
Module 12 : Exceptions
except aParticularError:
Stuff to do on error
9
10. try/except group
• If no exception in the try suite, skip all the
try/except to the next line of code.
• If an error occurs in a try suite, look for the
right exception.
• If found, run that except suite, and then
skip past the try/except group to the next
line of code.
• If no exception handling found, give the error
to Python.
Module 12 : Exceptions 10
12. An example
try:
print('Entering try suite') # trace
dividend = float(input('dividend:'))
divisor = float(input('divisor:'))
result = dividend/divisor
print('{:2.2f} divided by {:2.2f} = ’
'{:2.2f}'.format(dividend,divisor,result))
except ZeroDivisionError:
print('Divide by 0 error')
except ValueError:
print("Couldn't convert to a float")
print('Continuing with the rest of the program')
Module 12 : Exceptions
Try Suite
Except
Suite 1
Except
Suite 1
Try/Except Group
12