SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
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

Más contenido relacionado

Más de alvin567

Make hyperlink
Make hyperlinkMake hyperlink
Make hyperlinkalvin567
 
Lecture 10 user defined functions and modules
Lecture 10  user defined functions and modulesLecture 10  user defined functions and modules
Lecture 10 user defined functions and modulesalvin567
 
Lecture 9 composite types
Lecture 9  composite typesLecture 9  composite types
Lecture 9 composite typesalvin567
 
Lecture 8 strings and characters
Lecture 8  strings and charactersLecture 8  strings and characters
Lecture 8 strings and charactersalvin567
 
Lecture 7 program development issues (supplementary)
Lecture 7  program development issues (supplementary)Lecture 7  program development issues (supplementary)
Lecture 7 program development issues (supplementary)alvin567
 
Lecture 6.2 flow control repetition
Lecture 6.2  flow control repetitionLecture 6.2  flow control repetition
Lecture 6.2 flow control repetitionalvin567
 
Lecture 6.1 flow control selection
Lecture 6.1  flow control selectionLecture 6.1  flow control selection
Lecture 6.1 flow control selectionalvin567
 
Lecture 5 numbers and built in functions
Lecture 5  numbers and built in functionsLecture 5  numbers and built in functions
Lecture 5 numbers and built in functionsalvin567
 
Lecture 4 variables data types and operators
Lecture 4  variables data types and operatorsLecture 4  variables data types and operators
Lecture 4 variables data types and operatorsalvin567
 
Lecture 3 basic syntax and semantics
Lecture 3  basic syntax and semanticsLecture 3  basic syntax and semantics
Lecture 3 basic syntax and semanticsalvin567
 
Lecture 2 introduction to python
Lecture 2  introduction to pythonLecture 2  introduction to python
Lecture 2 introduction to pythonalvin567
 
Lecture 0 beginning
Lecture 0  beginningLecture 0  beginning
Lecture 0 beginningalvin567
 
Lecture 11 file management
Lecture 11  file managementLecture 11  file management
Lecture 11 file managementalvin567
 

Más de alvin567 (13)

Make hyperlink
Make hyperlinkMake hyperlink
Make hyperlink
 
Lecture 10 user defined functions and modules
Lecture 10  user defined functions and modulesLecture 10  user defined functions and modules
Lecture 10 user defined functions and modules
 
Lecture 9 composite types
Lecture 9  composite typesLecture 9  composite types
Lecture 9 composite types
 
Lecture 8 strings and characters
Lecture 8  strings and charactersLecture 8  strings and characters
Lecture 8 strings and characters
 
Lecture 7 program development issues (supplementary)
Lecture 7  program development issues (supplementary)Lecture 7  program development issues (supplementary)
Lecture 7 program development issues (supplementary)
 
Lecture 6.2 flow control repetition
Lecture 6.2  flow control repetitionLecture 6.2  flow control repetition
Lecture 6.2 flow control repetition
 
Lecture 6.1 flow control selection
Lecture 6.1  flow control selectionLecture 6.1  flow control selection
Lecture 6.1 flow control selection
 
Lecture 5 numbers and built in functions
Lecture 5  numbers and built in functionsLecture 5  numbers and built in functions
Lecture 5 numbers and built in functions
 
Lecture 4 variables data types and operators
Lecture 4  variables data types and operatorsLecture 4  variables data types and operators
Lecture 4 variables data types and operators
 
Lecture 3 basic syntax and semantics
Lecture 3  basic syntax and semanticsLecture 3  basic syntax and semantics
Lecture 3 basic syntax and semantics
 
Lecture 2 introduction to python
Lecture 2  introduction to pythonLecture 2  introduction to python
Lecture 2 introduction to python
 
Lecture 0 beginning
Lecture 0  beginningLecture 0  beginning
Lecture 0 beginning
 
Lecture 11 file management
Lecture 11  file managementLecture 11  file management
Lecture 11 file management
 

Último

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 

Último (20)

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 

Lecture 12 exceptions