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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (19)

Exception
ExceptionException
Exception
 
Python Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and AssertionsPython Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and Assertions
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
43c
43c43c
43c
 
Presentation1
Presentation1Presentation1
Presentation1
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
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?
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .Net
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 

Destacado

Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesP3 InfoTech Solutions Pvt. Ltd.
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4Binay Kumar Ray
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File ProcessingRanel Padon
 
Кортунов Никита. Как ускорить разработку приложений или есть ли жизнь после P...
Кортунов Никита. Как ускорить разработку приложений или есть ли жизнь после P...Кортунов Никита. Как ускорить разработку приложений или есть ли жизнь после P...
Кортунов Никита. Как ускорить разработку приложений или есть ли жизнь после P...AvitoTech
 
Вадим Дробинин. Защищаем себя и пользователей: руководство по безопасности
Вадим Дробинин. Защищаем себя и пользователей: руководство по безопасностиВадим Дробинин. Защищаем себя и пользователей: руководство по безопасности
Вадим Дробинин. Защищаем себя и пользователей: руководство по безопасностиAvitoTech
 
Андрей Юткин. Media Picker — to infinity and beyond
Андрей Юткин. Media Picker — to infinity and beyondАндрей Юткин. Media Picker — to infinity and beyond
Андрей Юткин. Media Picker — to infinity and beyondAvitoTech
 
TechLeads meetup: Макс Лапшин, Erlyvideo
TechLeads meetup: Макс Лапшин, ErlyvideoTechLeads meetup: Макс Лапшин, Erlyvideo
TechLeads meetup: Макс Лапшин, ErlyvideoBadoo Development
 
TechLeads meetup: Евгений Потапов, ITSumma
TechLeads meetup: Евгений Потапов, ITSumma TechLeads meetup: Евгений Потапов, ITSumma
TechLeads meetup: Евгений Потапов, ITSumma Badoo Development
 
TechLeads meetup: Алексей Рыбак, Badoo
TechLeads meetup: Алексей Рыбак, BadooTechLeads meetup: Алексей Рыбак, Badoo
TechLeads meetup: Алексей Рыбак, BadooBadoo Development
 
TechLeads meetup: Андрей Шелёхин, Tinkoff.ru
TechLeads meetup: Андрей Шелёхин, Tinkoff.ruTechLeads meetup: Андрей Шелёхин, Tinkoff.ru
TechLeads meetup: Андрей Шелёхин, Tinkoff.ruBadoo Development
 

Destacado (12)

Slick: A control plane for middleboxes
Slick: A control plane for middleboxesSlick: A control plane for middleboxes
Slick: A control plane for middleboxes
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and Packages
 
Python Modules
Python ModulesPython Modules
Python Modules
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File Processing
 
Кортунов Никита. Как ускорить разработку приложений или есть ли жизнь после P...
Кортунов Никита. Как ускорить разработку приложений или есть ли жизнь после P...Кортунов Никита. Как ускорить разработку приложений или есть ли жизнь после P...
Кортунов Никита. Как ускорить разработку приложений или есть ли жизнь после P...
 
Вадим Дробинин. Защищаем себя и пользователей: руководство по безопасности
Вадим Дробинин. Защищаем себя и пользователей: руководство по безопасностиВадим Дробинин. Защищаем себя и пользователей: руководство по безопасности
Вадим Дробинин. Защищаем себя и пользователей: руководство по безопасности
 
Андрей Юткин. Media Picker — to infinity and beyond
Андрей Юткин. Media Picker — to infinity and beyondАндрей Юткин. Media Picker — to infinity and beyond
Андрей Юткин. Media Picker — to infinity and beyond
 
TechLeads meetup: Макс Лапшин, Erlyvideo
TechLeads meetup: Макс Лапшин, ErlyvideoTechLeads meetup: Макс Лапшин, Erlyvideo
TechLeads meetup: Макс Лапшин, Erlyvideo
 
TechLeads meetup: Евгений Потапов, ITSumma
TechLeads meetup: Евгений Потапов, ITSumma TechLeads meetup: Евгений Потапов, ITSumma
TechLeads meetup: Евгений Потапов, ITSumma
 
TechLeads meetup: Алексей Рыбак, Badoo
TechLeads meetup: Алексей Рыбак, BadooTechLeads meetup: Алексей Рыбак, Badoo
TechLeads meetup: Алексей Рыбак, Badoo
 
TechLeads meetup: Андрей Шелёхин, Tinkoff.ru
TechLeads meetup: Андрей Шелёхин, Tinkoff.ruTechLeads meetup: Андрей Шелёхин, Tinkoff.ru
TechLeads meetup: Андрей Шелёхин, Tinkoff.ru
 

Similar a Python exceptions

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
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
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
 
exceptions in java
exceptions in javaexceptions in java
exceptions in javajaveed_mhd
 

Similar a Python exceptions (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
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java 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
 
exceptions in java
exceptions in javaexceptions in java
exceptions in java
 

Último

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 

Último (20)

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 

Python exceptions

  • 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()