SlideShare a Scribd company logo
Introduction to 
computational thinking
Module 12 : Exceptions
Module 12 : Exceptions
Asst Prof Michael Lees
Office: N4‐02c‐76
email: mhlees[at]ntu.edu.sg
1
Contents
1. Why & What are exceptions
2. Try/Except group
3. Exception Philosophy
4. else and finally suites
Module 12 : Exceptions
Chapter 14
2
Dealing with problems
• Most modern languages provide ways to deal 
with ‘exceptional’ situations
• Try to capture certain situations/failures and 
deal with them gracefully
• All about being a good programmer!
Module 12 : Exceptions 3
What counts as an exception
• Errors: Indexing past the end of a list, trying to 
open a nonexistent file, fetching a nonexistent 
key from a dictionary, etc.
• Events: Search algorithm doesn’t find a value (not 
really an error), mail message arrives, queue 
event occurs.
• Ending conditions: File should be closed at the 
end of processing, list should be sorted after 
being filled.
• Weird stuff: For rare events, keep from clogging 
your code with lots of if statements. 
Module 12 : Exceptions 4
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
Bad input
• In general, we have assumed that the input 
we receive is correct (from a file, from the 
user).
• This is almost never true. There is always the 
chance that the input could be wrong.
• Our programs should be able to handle this.
• "Writing Secure Code,” by Howard and LeBlanc
– “All input is evil until proven otherwise.”
Module 12 : Exceptions 6
General form v1
try:
Code to run
except aParticularError:
Stuff to do on error
Module 12 : Exceptions 7
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
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
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
Module 12 : Exceptions 11
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
What exceptions are there?
• In the present Python, there is a set of 
exceptions that are pre‐labeled.
• To find the exception for a case you are 
interested in, easy enough to try it in the 
interpreter and see what comes up.
3/0 =>
ZeroDivisionError: integer division or modulo by
zero
Module 12 : Exceptions 13
Module 12 : Exceptions
Details: http://docs.python.org/library/exceptions.html
14
EXCEPTION PHILOSOPHY
Module 12 : Exceptions
Module 12 : Exceptions 15
How you deal with problems
Two ways to deal with exceptions:
• LBYL: Look Before you Leap
• EAFP: Easier to Ask Forgiveness 
than Permission (famous quote 
by Grace Hopper)
Module 12 : Exceptions 16
Look before you leap
• Super cautious!
• Check all aspects before executing
– If string required : check that
– if values should be positive : check that
• What happens to length of code?
• And readability of code – code is hidden in 
checking.
Module 12 : Exceptions 17
Easier to ask forgiveness than 
permission
• Run anything you like!
• Be ready to clean up in case of error.
• The try suite code reflects what you want to 
do, and the except code what you want to 
do on error. Cleaner separation!
Module 12 : Exceptions 18
A Choice
• Python programmers support the EAFP approach:
– Run the code (in try) and used except suites to deal 
with errors (don’t check first)
Module 12 : Exceptions
if not isinstance(s, str) or not s.isdigit:
return None
elif len(s) > 10: # too many digits to convert
return None
else:
return int(str)
try:
return int(str)
except (TypeError, ValueError, OverflowError):
return None
LBYL
EAFP
19
OTHER SUITES
Module 12 : Exceptions
Module 12 : Exceptions 20
else suite
• The else suite is used to execute specific code 
when no exception occurs
Module 12 : Exceptions
try:
Code to run
except aParticularError:
Stuff to do on error
else
Stuff to do when no error
21
finally suite
• The finally suite is used to execute code at the 
end of try/except group (with or without 
error)
Module 12 : Exceptions
try:
Code to run
except aParticularError:
Stuff to do on error
finally
Stuff to do always at end
22
Challenge 12.1 Calculation errors
Modify the calculator example from module 4 to capture some common 
exceptions.
Module 12 : Exceptions
ERROR!
23
Thought process
• What errors can the code generate?
• Capture the common ones and give clear 
instruction
• Use the else condition to print out answer 
only when no error
Module 12 : Exceptions 24
Take home lessons
• Using exception handling to help users is 
important!
• Different types of exceptions: events, errors, 
etc.
• LYBL vs. EAFP
• try‐except‐else‐finally suites (in many 
languages)
Module 12 : Exceptions 25
Further reading
• http://docs.python.org/tutorial/errors.html
• http://diveintopython.org/file_handling/index
.html
• http://oranlooney.com/lbyl‐vs‐eafp/
Module 12 : Exceptions 26

More Related Content

Similar to Lecture 12 exceptions (20)

PDF
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
PDF
Python Programming - X. Exception Handling and Assertions
Ranel Padon
 
PPTX
Python Exceptions Powerpoint Presentation
mitchellblack733
 
PPT
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
PPT
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
PPTX
Exception handling.pptxnn h
sabarivelan111007
 
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
PPTX
Exception Handling in Python topic .pptx
mitu4846t
 
PPTX
Exception Handling in python programming.pptx
shririshsri
 
PPTX
exception handling.pptx
AbinayaC11
 
PDF
Exception handling in python
Lifna C.S
 
PPTX
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
PPTX
Exception handling.pptx
NISHASOMSCS113
 
PDF
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
PPTX
Exception handling with python class 12.pptx
PreeTVithule1
 
PPTX
Python Lecture 7
Inzamam Baig
 
PPT
Exception Handling using Python Libraries
mmvrm
 
PPT
Exception handling in python and how to handle it
s6901412
 
PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
Python Programming - X. Exception Handling and Assertions
Ranel Padon
 
Python Exceptions Powerpoint Presentation
mitchellblack733
 
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
Exception handling.pptxnn h
sabarivelan111007
 
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
Exception Handling in Python topic .pptx
mitu4846t
 
Exception Handling in python programming.pptx
shririshsri
 
exception handling.pptx
AbinayaC11
 
Exception handling in python
Lifna C.S
 
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
Exception handling.pptx
NISHASOMSCS113
 
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
Exception handling with python class 12.pptx
PreeTVithule1
 
Python Lecture 7
Inzamam Baig
 
Exception Handling using Python Libraries
mmvrm
 
Exception handling in python and how to handle it
s6901412
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 

More from alvin567 (13)

PPT
Make hyperlink
alvin567
 
PDF
Lecture 10 user defined functions and modules
alvin567
 
PDF
Lecture 9 composite types
alvin567
 
PDF
Lecture 8 strings and characters
alvin567
 
PDF
Lecture 7 program development issues (supplementary)
alvin567
 
PDF
Lecture 6.2 flow control repetition
alvin567
 
PDF
Lecture 6.1 flow control selection
alvin567
 
PDF
Lecture 5 numbers and built in functions
alvin567
 
PDF
Lecture 4 variables data types and operators
alvin567
 
PDF
Lecture 3 basic syntax and semantics
alvin567
 
PDF
Lecture 2 introduction to python
alvin567
 
PDF
Lecture 0 beginning
alvin567
 
PDF
Lecture 11 file management
alvin567
 
Make hyperlink
alvin567
 
Lecture 10 user defined functions and modules
alvin567
 
Lecture 9 composite types
alvin567
 
Lecture 8 strings and characters
alvin567
 
Lecture 7 program development issues (supplementary)
alvin567
 
Lecture 6.2 flow control repetition
alvin567
 
Lecture 6.1 flow control selection
alvin567
 
Lecture 5 numbers and built in functions
alvin567
 
Lecture 4 variables data types and operators
alvin567
 
Lecture 3 basic syntax and semantics
alvin567
 
Lecture 2 introduction to python
alvin567
 
Lecture 0 beginning
alvin567
 
Lecture 11 file management
alvin567
 
Ad

Recently uploaded (20)

PDF
July Patch Tuesday
Ivanti
 
PDF
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PDF
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
PPTX
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
PPTX
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
PDF
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
July Patch Tuesday
Ivanti
 
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
Ad

Lecture 12 exceptions