SlideShare a Scribd company logo
1 of 21
Download to read offline
Python Exceptions
Exception handling in Python
Tim Muller & Rik van Achterberg | 07-08-2013
Coding styles: LBYL vs EAFP
● Look Before You Leap
○ “[...] explicitly tests for pre-conditions before making calls or
lookups. This style contrasts with the EAFP approach and is
characterized by the presence of many if statements.”
● Easier to Ask for Forgiveness than Permission
○ “[...] assumes the existence of valid keys or attributes and catches
exceptions if the assumption proves false. This clean and fast style
is characterized by the presence of many try and except
statements. The technique contrasts with the LBYL style common
to many other languages such as C.”
When to use
“All errors are exceptions, but not all exceptions are errors”
Use exception handling to gracefully recover from application errors.
But: It’s perfectly allowed, and sometimes necessary, to utilize
exception handling for general application control flow.
(EOFError, for example)
We all know this
try:
execute_some_code()
except:
handle_gracefully()
try:
execute_some_code()
except:
handle_gracefully()
We all know this
● Main action:
○ Code to be executed that potentially might cause exception(s)
● Exception handler:
○ Code that recovers from an exception
Exception handler
Main action
But don’t do it.
Catching too broad exceptions is potentially dangerous.
Among others, this “wildcard” handler will catch:
● system exit triggers
● memory errors
● typos
● anything else you might not have considered
try:
execute_some_code()
except:
handle_gracefully()
Better:
Catching specific exceptions
try:
execute_some_code()
except SomeException:
handle_gracefully()
Catching multiple exceptions
Handling them all the same way
try:
execute_some_code()
except (SomeException, AnotherException):
handle_gracefully()
Catching multiple exceptions
Handling them separately
try:
execute_some_code()
except SomeException:
handle_gracefully()
except AnotherException:
do_another_thing()
Raising exceptions
Exceptions can be raised using raise <exception>
with optional arguments.
raise RuntimeError
raise RuntimeError ()
raise RuntimeError ("error message" )
raise RuntimeError , "error message"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: error message
Accessing the exception
Use “as” to access the exception object
(using a comma is deprecated)
try:
raise RuntimeError ("o hai")
except RuntimeError as e:
print e.message
>>> o hai
Propagating exceptions
Try-blocks can be nested;
All exceptions propagate to the top-level “root exception handler” if
uncaught.
The (default) root exception handler terminates
the Python process.
try:
try:
raise SomeException
except SomeException:
print "Inner"
except SomeException:
print "Outer"
>>> Inner
Propagating exceptions
Try-blocks can be nested;
All exceptions propagate to the top-level “root exception handler” if
uncaught.
try:
try:
raise SomeException
except AnotherException:
print "Inner"
except SomeException:
print "Outer"
>>> Outer
Propagating exceptions
Propagation can be forced by using raise without arguments.
this re-raises the most recent exception
This is useful for e.g. exception logging .
try:
try:
raise SomeException
except SomeException:
print "Propagating"
raise
except SomeException:
print "Outer"
>>> Propagating
>>> Outer
More cool stuff
Code in the finally block will always be executed*
Write termination actions here.
* Unless Python crashes completely
try:
open_file()
except IOError:
print "Exception caught"
finally:
close_file()
More cool stuff
Code in the finally block will always be executed
it’s not even necessary to specify a handler.
This code will propagate any exception.
try:
open_file()
finally:
close_file()
More cool stuff
Code in the else block will be executed when no exception is raised
try:
open_file()
except IOError:
print "Exception caught"
else:
print "Everything went according to plan"
finally:
close_file()
Exception matching
Exceptions are matched by superclass relationships.
try:
raise RuntimeError
except Exception as e:
print e.__class__
# <type 'exceptions.RuntimeError'>
BaseException
Exception
StandardError
RuntimeError
Exception matching
Exceptions are matched by superclass relationships.
This way, exception hierarchies can be designed.
For example, OverflowError, ZeroDivisionError and FloatingPointError
are all subclasses of ArithmeticError.
Just write a handler for ArithmeticError to catch any of them.
Writing your own
It’s as simple as
class MyException (MyBaseException):
pass
raise HandException(question)
try:
raise HandException( "I have a question" )
except HandException:
question = raw_input()
answer = generate_answer(question)
raise AnswerException(answer)
finally:
talks.next()

More Related Content

What's hot

Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception handling in Python
Exception handling in PythonException handling in Python
Exception handling in PythonAdnan Siddiqi
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handlingNahian Ahmed
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingMegha V
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in cMemo Yekem
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling sharqiyem
 
14 exception handling
14 exception handling14 exception handling
14 exception handlingjigeno
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Exceptionhandling
ExceptionhandlingExceptionhandling
ExceptionhandlingNuha Noor
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Javaparag
 

What's hot (20)

Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in Python
Exception handling in PythonException handling in Python
Exception handling in Python
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Presentation1
Presentation1Presentation1
Presentation1
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
43c
43c43c
43c
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 

Similar to Exception Handling in Python - Rik van Achterberg & Tim Muller

Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxPavan326406
 
Exception Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptException Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptRaja Ram Dutta
 
Exception handling.pptx
Exception handling.pptxException handling.pptx
Exception handling.pptxNISHASOMSCS113
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16Max Kleiner
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaRajkattamuri
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
exception handling.pptx
exception handling.pptxexception handling.pptx
exception handling.pptxAbinayaC11
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in PythonDrJasmineBeulahG
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 

Similar to Exception Handling in Python - Rik van Achterberg & Tim Muller (20)

Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Exception Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptException Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.ppt
 
Exception handling.pptx
Exception handling.pptxException handling.pptx
Exception handling.pptx
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
 
21 ruby exceptions
21 ruby exceptions21 ruby exceptions
21 ruby exceptions
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
exception handling.pptx
exception handling.pptxexception handling.pptx
exception handling.pptx
 
Unit 5
Unit 5Unit 5
Unit 5
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
41c
41c41c
41c
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

More from Byte

Beaumotica.com & Magento 2 - Meet Magento 2016
Beaumotica.com & Magento 2 -  Meet Magento 2016Beaumotica.com & Magento 2 -  Meet Magento 2016
Beaumotica.com & Magento 2 - Meet Magento 2016Byte
 
Hackers traced - Meet Magento 2016
Hackers traced -  Meet Magento 2016Hackers traced -  Meet Magento 2016
Hackers traced - Meet Magento 2016Byte
 
Magento 2 performance - a benchmark
Magento 2 performance - a benchmarkMagento 2 performance - a benchmark
Magento 2 performance - a benchmarkByte
 
Presentatie snelheid ecl
Presentatie snelheid eclPresentatie snelheid ecl
Presentatie snelheid eclByte
 
Workshop New Relic - juni 2015
Workshop New Relic - juni 2015Workshop New Relic - juni 2015
Workshop New Relic - juni 2015Byte
 
Google Webmasters Tools
Google Webmasters ToolsGoogle Webmasters Tools
Google Webmasters ToolsByte
 
APMG juni 2014 - Regular Expression
APMG juni 2014 - Regular ExpressionAPMG juni 2014 - Regular Expression
APMG juni 2014 - Regular ExpressionByte
 
Hypernode Pitch @ Meet Magento 2014
Hypernode Pitch @ Meet Magento 2014Hypernode Pitch @ Meet Magento 2014
Hypernode Pitch @ Meet Magento 2014Byte
 
Joomladagen 2014 - Google Tag Manager
Joomladagen 2014 - Google Tag ManagerJoomladagen 2014 - Google Tag Manager
Joomladagen 2014 - Google Tag ManagerByte
 
Hexagonal Design - Maarten van Schaik
Hexagonal Design - Maarten van SchaikHexagonal Design - Maarten van Schaik
Hexagonal Design - Maarten van SchaikByte
 
Presentatie MUG 27 juni 2013 - Graphite/New Relic
Presentatie MUG 27 juni 2013 - Graphite/New RelicPresentatie MUG 27 juni 2013 - Graphite/New Relic
Presentatie MUG 27 juni 2013 - Graphite/New RelicByte
 
Mm13 nl presentatie byte
Mm13 nl presentatie byteMm13 nl presentatie byte
Mm13 nl presentatie byteByte
 
Site gehacked... hoe op te lossen?
 Site gehacked... hoe op te lossen? Site gehacked... hoe op te lossen?
Site gehacked... hoe op te lossen?Byte
 
Varnish & Magento
Varnish & MagentoVarnish & Magento
Varnish & MagentoByte
 
Redis - Magento User Group
Redis - Magento User GroupRedis - Magento User Group
Redis - Magento User GroupByte
 
Help! My site has been hacked!
Help! My site has been hacked!Help! My site has been hacked!
Help! My site has been hacked!Byte
 
Byte hackpreventie
Byte hackpreventieByte hackpreventie
Byte hackpreventieByte
 
Magento Speed Analysis - Meet Magento 2012
Magento Speed Analysis - Meet Magento 2012Magento Speed Analysis - Meet Magento 2012
Magento Speed Analysis - Meet Magento 2012Byte
 
Hosting & Onderhoud Joomladagen 2012
Hosting & Onderhoud Joomladagen 2012Hosting & Onderhoud Joomladagen 2012
Hosting & Onderhoud Joomladagen 2012Byte
 
10 Joomla vragen - Joomladagen 2010
10 Joomla vragen - Joomladagen 201010 Joomla vragen - Joomladagen 2010
10 Joomla vragen - Joomladagen 2010Byte
 

More from Byte (20)

Beaumotica.com & Magento 2 - Meet Magento 2016
Beaumotica.com & Magento 2 -  Meet Magento 2016Beaumotica.com & Magento 2 -  Meet Magento 2016
Beaumotica.com & Magento 2 - Meet Magento 2016
 
Hackers traced - Meet Magento 2016
Hackers traced -  Meet Magento 2016Hackers traced -  Meet Magento 2016
Hackers traced - Meet Magento 2016
 
Magento 2 performance - a benchmark
Magento 2 performance - a benchmarkMagento 2 performance - a benchmark
Magento 2 performance - a benchmark
 
Presentatie snelheid ecl
Presentatie snelheid eclPresentatie snelheid ecl
Presentatie snelheid ecl
 
Workshop New Relic - juni 2015
Workshop New Relic - juni 2015Workshop New Relic - juni 2015
Workshop New Relic - juni 2015
 
Google Webmasters Tools
Google Webmasters ToolsGoogle Webmasters Tools
Google Webmasters Tools
 
APMG juni 2014 - Regular Expression
APMG juni 2014 - Regular ExpressionAPMG juni 2014 - Regular Expression
APMG juni 2014 - Regular Expression
 
Hypernode Pitch @ Meet Magento 2014
Hypernode Pitch @ Meet Magento 2014Hypernode Pitch @ Meet Magento 2014
Hypernode Pitch @ Meet Magento 2014
 
Joomladagen 2014 - Google Tag Manager
Joomladagen 2014 - Google Tag ManagerJoomladagen 2014 - Google Tag Manager
Joomladagen 2014 - Google Tag Manager
 
Hexagonal Design - Maarten van Schaik
Hexagonal Design - Maarten van SchaikHexagonal Design - Maarten van Schaik
Hexagonal Design - Maarten van Schaik
 
Presentatie MUG 27 juni 2013 - Graphite/New Relic
Presentatie MUG 27 juni 2013 - Graphite/New RelicPresentatie MUG 27 juni 2013 - Graphite/New Relic
Presentatie MUG 27 juni 2013 - Graphite/New Relic
 
Mm13 nl presentatie byte
Mm13 nl presentatie byteMm13 nl presentatie byte
Mm13 nl presentatie byte
 
Site gehacked... hoe op te lossen?
 Site gehacked... hoe op te lossen? Site gehacked... hoe op te lossen?
Site gehacked... hoe op te lossen?
 
Varnish & Magento
Varnish & MagentoVarnish & Magento
Varnish & Magento
 
Redis - Magento User Group
Redis - Magento User GroupRedis - Magento User Group
Redis - Magento User Group
 
Help! My site has been hacked!
Help! My site has been hacked!Help! My site has been hacked!
Help! My site has been hacked!
 
Byte hackpreventie
Byte hackpreventieByte hackpreventie
Byte hackpreventie
 
Magento Speed Analysis - Meet Magento 2012
Magento Speed Analysis - Meet Magento 2012Magento Speed Analysis - Meet Magento 2012
Magento Speed Analysis - Meet Magento 2012
 
Hosting & Onderhoud Joomladagen 2012
Hosting & Onderhoud Joomladagen 2012Hosting & Onderhoud Joomladagen 2012
Hosting & Onderhoud Joomladagen 2012
 
10 Joomla vragen - Joomladagen 2010
10 Joomla vragen - Joomladagen 201010 Joomla vragen - Joomladagen 2010
10 Joomla vragen - Joomladagen 2010
 

Recently uploaded

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 

Recently uploaded (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

Exception Handling in Python - Rik van Achterberg & Tim Muller

  • 1. Python Exceptions Exception handling in Python Tim Muller & Rik van Achterberg | 07-08-2013
  • 2. Coding styles: LBYL vs EAFP ● Look Before You Leap ○ “[...] explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.” ● Easier to Ask for Forgiveness than Permission ○ “[...] assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.”
  • 3. When to use “All errors are exceptions, but not all exceptions are errors” Use exception handling to gracefully recover from application errors. But: It’s perfectly allowed, and sometimes necessary, to utilize exception handling for general application control flow. (EOFError, for example)
  • 4. We all know this try: execute_some_code() except: handle_gracefully()
  • 5. try: execute_some_code() except: handle_gracefully() We all know this ● Main action: ○ Code to be executed that potentially might cause exception(s) ● Exception handler: ○ Code that recovers from an exception Exception handler Main action
  • 6. But don’t do it. Catching too broad exceptions is potentially dangerous. Among others, this “wildcard” handler will catch: ● system exit triggers ● memory errors ● typos ● anything else you might not have considered try: execute_some_code() except: handle_gracefully()
  • 8. Catching multiple exceptions Handling them all the same way try: execute_some_code() except (SomeException, AnotherException): handle_gracefully()
  • 9. Catching multiple exceptions Handling them separately try: execute_some_code() except SomeException: handle_gracefully() except AnotherException: do_another_thing()
  • 10. Raising exceptions Exceptions can be raised using raise <exception> with optional arguments. raise RuntimeError raise RuntimeError () raise RuntimeError ("error message" ) raise RuntimeError , "error message" Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: error message
  • 11. Accessing the exception Use “as” to access the exception object (using a comma is deprecated) try: raise RuntimeError ("o hai") except RuntimeError as e: print e.message >>> o hai
  • 12. Propagating exceptions Try-blocks can be nested; All exceptions propagate to the top-level “root exception handler” if uncaught. The (default) root exception handler terminates the Python process. try: try: raise SomeException except SomeException: print "Inner" except SomeException: print "Outer" >>> Inner
  • 13. Propagating exceptions Try-blocks can be nested; All exceptions propagate to the top-level “root exception handler” if uncaught. try: try: raise SomeException except AnotherException: print "Inner" except SomeException: print "Outer" >>> Outer
  • 14. Propagating exceptions Propagation can be forced by using raise without arguments. this re-raises the most recent exception This is useful for e.g. exception logging . try: try: raise SomeException except SomeException: print "Propagating" raise except SomeException: print "Outer" >>> Propagating >>> Outer
  • 15. More cool stuff Code in the finally block will always be executed* Write termination actions here. * Unless Python crashes completely try: open_file() except IOError: print "Exception caught" finally: close_file()
  • 16. More cool stuff Code in the finally block will always be executed it’s not even necessary to specify a handler. This code will propagate any exception. try: open_file() finally: close_file()
  • 17. More cool stuff Code in the else block will be executed when no exception is raised try: open_file() except IOError: print "Exception caught" else: print "Everything went according to plan" finally: close_file()
  • 18. Exception matching Exceptions are matched by superclass relationships. try: raise RuntimeError except Exception as e: print e.__class__ # <type 'exceptions.RuntimeError'> BaseException Exception StandardError RuntimeError
  • 19. Exception matching Exceptions are matched by superclass relationships. This way, exception hierarchies can be designed. For example, OverflowError, ZeroDivisionError and FloatingPointError are all subclasses of ArithmeticError. Just write a handler for ArithmeticError to catch any of them.
  • 20. Writing your own It’s as simple as class MyException (MyBaseException): pass
  • 21. raise HandException(question) try: raise HandException( "I have a question" ) except HandException: question = raw_input() answer = generate_answer(question) raise AnswerException(answer) finally: talks.next()