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

PDF
Lecture 1 computing and algorithms
ODP
Understanding the lock manager internals with the fb lock print utility
PDF
Os Goodger
PPT
E-Commerce Security - Application attacks - Server Attacks
PPTX
CAPTCHA
PPTX
Captcha seminar
PPT
Concurrency control
Lecture 1 computing and algorithms
Understanding the lock manager internals with the fb lock print utility
Os Goodger
E-Commerce Security - Application attacks - Server Attacks
CAPTCHA
Captcha seminar
Concurrency control

Similar to Lecture 12 exceptions (20)

PDF
Python programming : Exceptions
PDF
Python Programming - X. Exception Handling and Assertions
PPTX
Python Exceptions Powerpoint Presentation
PPT
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
PPT
Exception Handling on 22nd March 2022.ppt
PPTX
Exception handling.pptxnn h
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
PPTX
Exception Handling in Python topic .pptx
PPTX
Exception Handling in python programming.pptx
PPTX
exception handling.pptx
PDF
Exception handling in python
PPTX
Python Exception handling using Try-Except-Finally
PPTX
Exception handling.pptx
PDF
Exception-Handling Exception-HandlingFpptx.pdf
PPTX
Exception handling with python class 12.pptx
PPTX
Python Lecture 7
PPT
Exception Handling using Python Libraries
PPT
Exception handling in python and how to handle it
PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Python programming : Exceptions
Python Programming - X. Exception Handling and Assertions
Python Exceptions Powerpoint Presentation
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
Exception Handling on 22nd March 2022.ppt
Exception handling.pptxnn h
lecs101.pdfgggggggggggggggggggddddddddddddb
Exception Handling in Python topic .pptx
Exception Handling in python programming.pptx
exception handling.pptx
Exception handling in python
Python Exception handling using Try-Except-Finally
Exception handling.pptx
Exception-Handling Exception-HandlingFpptx.pdf
Exception handling with python class 12.pptx
Python Lecture 7
Exception Handling using Python Libraries
Exception handling in python and how to handle it
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Ad

More from alvin567 (13)

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

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Empathic Computing: Creating Shared Understanding
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Electronic commerce courselecture one. Pdf
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
Advanced IT Governance
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Cloud computing and distributed systems.
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
cuic standard and advanced reporting.pdf
Big Data Technologies - Introduction.pptx
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Empathic Computing: Creating Shared Understanding
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Electronic commerce courselecture one. Pdf
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Spectral efficient network and resource selection model in 5G networks
Sensors and Actuators in IoT Systems using pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
madgavkar20181017ppt McKinsey Presentation.pdf
Advanced IT Governance
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Cloud computing and distributed systems.
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Chapter 3 Spatial Domain Image Processing.pdf
cuic standard and advanced reporting.pdf

Lecture 12 exceptions