2. Disclaimer: This presentation is prepared by trainees of
baabtra as a part of mentoring program. This is not official
document of baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .
Ltd
3. Title of the presentation
Reshmi R
reshmir@ymail.com
www.facebook.com/reshmi.
ramaswami
twitter.com/reshmir1
in.linkedin.com/in/reshmi r
+917736719717
4. Handling Exceptions
• Exception: An error that occurs during the execution of a
program
• Exception is raised and can be caught (or trapped) then
handled
• Unhandled, an exception halts the program and an error
message is displayed
>>> 1/0
Traceback (most recent call last):
File "<pyshell#0>", line 1, in -toplevel-
1/0
ZeroDivisionError: integer division or modulo by zero
5. Try/Except
try:
num = float(raw_input("Enter a number: "))
except:
print "Something went wrong!"
• ‘try’ statement sections of code that could raise exception
• If an exception is raised, then the ‘except’ block is run
• If no exception is raised, then the ‘except’ block is skipped
6. Try/Finally
• In try/finally, finally block is always run whether an exception
occurs or not
try:
<block of statements>
finally:
<block of statements>
• Ensure some actions to be done in any case
• It can not be used in the try with except and else.
7. Specifying an Exception Type
try:
num = float(raw_input("nEnter a number: "))
except(ValueError):
print "That was not a number!“
• Different types of errors raise different types of exceptions
• except clause can specify exception types to handle
• Attempt to convert "Hi!" to float raises ValueError exception
• Avoid general, catch-all exception handling
• Specify exception types to handle each individual case
8. Handling Multiple Exception Types
(contd…)
for value in (None, "Hi!"):
try:
print "Attempting to convert", value, "–>",
print float(value)
except(TypeError):
print "Can only convert string or number!"
except(ValueError):
print "Can only convert a string of digits!“
• Each except clause can offer specific code for each individual
exception type
9. Try/Else
try:
num = float(raw_input("nEnter a number: "))
except(ValueError):
print "That was not a number!"
else:
print "You entered the number", num
• Can add single else clause after all except clauses
• else block executes only if no exception is raised
• num printed only if assignment statement in the try block
raises no exception
10. If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com