SlideShare a Scribd company logo
PYTHON PROGRAMMING

Engr. Ranel O. Padon

X. EXCEPTION HANDLING
PYTHON PROGRAMMING TOPICS
I

• Introduction to Python Programming

II

• Python Basics

III

• Controlling the Program Flow

IV

• Program Components: Functions, Classes, Packages, and Modules

V

• Sequences (List and Tuples), and Dictionaries

VI

• Object-Based Programming: Classes and Objects

VII

• Customizing Classes and Operator Overloading

VIII

• Object-Oriented Programming: Inheritance and Polymorphism

IX

• Randomization Algorithms

X

• Exception Handling and Assertions

XI

• String Manipulation and Regular Expressions

XII

• File Handling and Processing

XIII

• GUI Programming Using Tkinter
Python Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and Assertions
try
except

Defensive
Programming

else
finally

raise
assert
class Exception
Python Programming - X. Exception Handling and Assertions
http://www.newser.com/story/20282/china-atm-glitch-nets-man-life.html
http://www.newser.com/story/148427/atm-error-lets-man-withdraw-15m-gamble-it-away.html
INTRODUCTION

Exception is an indication of a special event that
occurs during a program’s execution.

Exception indicates that, although the event can occur,
the event occurs infrequently.
INTRODUCTION
INTRODUCTION

When a Python script encounters a situation that
it can't cope with, it raises an exception.

An exception is a Python object that represents an error.
INTRODUCTION
INTRODUCTION
INTRODUCTION | Exceptions
1.
2.
3.
4.
5.
6.
7.
8.
9.

Division by Zero
Addition of two incompatible types.
Accessing a file that is nonexistent.
Accessing a nonexistent index of a sequence.
Deleting a table in a disconnected database server.
Withdrawing money greater than the available amount.
Invalid input bearing angle.
Negative perimeter distance.
…
INTRODUCTION | Exceptions
Resource Leak
Aborting a program component could leave a file or a network
connection in a state in which other programs
are not able to acquire the resource.
EXCEPTION HANDLING
EXCEPTION HANDLING
Advantages
1. handle the error
- catching the exception
- resolving the exception
2. continue processing as if no error had occured
3. programs are more clear, robust and more fault-tolerant
EXCEPTION HANDLING
When no exceptions occur, exception-handling code
incurs little or no performance penalties.
Programs that implement exception handling operate more
efficiently than programs that perform error handling throughout
the program logic.
EXCEPTION HANDLING
Brute-Force Error Handling
EXCEPTION HANDLING
Brute-Force Error Handling
it may work, but intermixing the logic of the program
with the error-handling logic can make the program difficult
to read, modify, maintain and debug—especially in large
applications.
EXCEPTION HANDLING

Exception handling enables the programmer to
remove error-handling code from the “main line”
of the program’s execution.
This improves program clarity and enhances modifiability.
EXCEPTION HANDLING | Python
Mechanism is similar with that used in Modula-3, C# and Java.
Not all programming languages support exception handling.
EXCEPTION HANDLING
EXCEPTION HANDLING | try-except
EXCEPTION HANDLING | try-except
Python uses try statements to enable exception handling.
The try statement encloses statements
that potentially cause exceptions.
A try statement consists of keyword try, followed by a colon
(:), followed by a suite of code in which exceptions may occur,
followed by one or more clauses.
EXCEPTION HANDLING | try-except
Immediately following the try suite may be
one or more except clauses
(also called except handlers).
Each except clause specifies zero or more
exception names that represent the type(s)
of exceptions the except clause can handle.
EXCEPTION HANDLING | try-except

If an exception occurs in a try suite,
the try suite expires and program control
transfers to the first matching except handler
(if there is one) following the try suite.
EXCEPTION HANDLING | try-except

an except handler always should specify the name
of the exception to catch.

an empty except handler should be used only for a
default catch-all case.
EXCEPTION HANDLING | try-except

If no exceptions occur in a try suite,
the interpreter ignores the exception handlers
for that try statement.
EXCEPTION HANDLING | try-except
EXCEPTION HANDLING | else

After the last except clause, an optional else clause
contains code that executes if the code in
the try suite raised no exceptions.
EXCEPTION HANDLING | Summary
EXCEPTION HANDLING | Summary
EXCEPTION HANDLING | Summary
EXCEPTION HANDLING | Summary
EXCEPTION HANDLING | finally

A try suite can be followed by zero except clauses;
in that case, it must be followed by a finally clause.
The code in the finally suite always executes,
regardless of whether an exception occurs.
EXCEPTION HANDLING | finally

Programs frequently request and release resources dynamically.
Programs that obtain certain types of resources (such as files)
sometimes must return those resources explicitly to the system
to avoid resource leaks.
EXCEPTION HANDLING | finally

The finally clause is an ideal location to place
resource deallocation code for resources acquired.
EXCEPTION HANDLING | finally
EXCEPTION HANDLING | finally
EXCEPTION HANDLING | finally
EXCEPTION HANDLING | finally
EXCEPTION HANDLING | Exception

Exceptions are objects of classes that inherit
from class Exception.
Programmer-defined exception classes should
derive directly or indirectly from class Exception.
class Exception
class Exception
(1/2)
class Exception
(2/2)
EXCEPTION HANDLING | raise
Raising/Throwing An Exception
raise keyword

Catching and handling exceptions enables a
program to know when an error has occurred, then to take
actions to minimize the consequences of that error.
EXCEPTION HANDLING | raise

The raise statement may specify an argument or
arguments that initialize the exception object.
In this case, a comma follows the exception name, and the
argument or a tuple of arguments follows the comma.
EXCEPTION HANDLING | raise Args
EXCEPTION HANDLING | raise Args
EXCEPTION HANDLING | Custom
EXCEPTION HANDLING | Custom
EXCEPTION HANDLING | Custom
EXCEPTION HANDLING | assert
An assertion is a sanity-check that you can turn on/off
when you are done with your testing of the program.
Assertion is like a raise-if statement
(or to be more accurate, a raise-if-not statement).
An expression is tested, and if the result comes up false,
an exception is raised.
EXCEPTION HANDLING | assert
Programmers often place assertions
at the start of a function to check for valid input,
and after a function call to check for valid output.
EXCEPTION HANDLING | assert
EXCEPTION HANDLING | assert
EXCEPTION HANDLING | assert
EXCEPTION HANDLING | assert
EXCEPTION HANDLING | assert
EXCEPTION HANDLING | assert
EXCEPTION HANDLING
EXCEPTION HANDLING
REFERENCES
 Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001).

 Disclaimer: Most of the images/information used here have no proper source
citation, and I do not claim ownership of these either. I don’t want to reinvent the
wheel, and I just want to reuse and reintegrate materials that I think are useful or
cool, then present them in another light, form, or perspective. Moreover, the
images/information here are mainly used for illustration/educational purposes only,
in the spirit of openness of data, spreading light, and empowering people with
knowledge. 
Thank You!

More Related Content

What's hot (20)

PPTX
Properties and indexers in C#
Hemant Chetwani
 
PDF
9 python data structure-2
Prof. Dr. K. Adisesha
 
PPTX
Deque and its applications
Jsaddam Hussain
 
PPTX
class and objects
Payel Guria
 
PPT
stack and queue array implementation in java.
CIIT Atd.
 
PPTX
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
PPTX
Iterarators and generators in python
Sarfaraz Ghanta
 
PPTX
Recursive Function
Harsh Pathak
 
PPTX
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
PDF
Exception handling in plsql
Arun Sial
 
PPTX
Operator overloading and type conversions
Amogh Kalyanshetti
 
PDF
07 java collection
Abhishek Khune
 
PPTX
Java - Collections framework
Riccardo Cardin
 
PPTX
Data Types, Variables, and Operators
Marwa Ali Eissa
 
PPTX
Java Stack Data Structure.pptx
vishal choudhary
 
PPTX
Python Lambda Function
Md Soyaib
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
Properties and indexers in C#
Hemant Chetwani
 
9 python data structure-2
Prof. Dr. K. Adisesha
 
Deque and its applications
Jsaddam Hussain
 
class and objects
Payel Guria
 
stack and queue array implementation in java.
CIIT Atd.
 
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Iterarators and generators in python
Sarfaraz Ghanta
 
Recursive Function
Harsh Pathak
 
Exception handling in plsql
Arun Sial
 
Operator overloading and type conversions
Amogh Kalyanshetti
 
07 java collection
Abhishek Khune
 
Java - Collections framework
Riccardo Cardin
 
Data Types, Variables, and Operators
Marwa Ali Eissa
 
Java Stack Data Structure.pptx
vishal choudhary
 
Python Lambda Function
Md Soyaib
 
Functions in c++
Rokonuzzaman Rony
 

Viewers also liked (12)

PDF
Python Programming - IX. On Randomness
Ranel Padon
 
PDF
Python Programming - VIII. Inheritance and Polymorphism
Ranel Padon
 
PDF
Python Programming - III. Controlling the Flow
Ranel Padon
 
PDF
Python Programming - V. Sequences (List and Tuples) and Dictionaries
Ranel Padon
 
PDF
Switchable Map APIs with Drupal
Ranel Padon
 
PDF
Python Programming - VII. Customizing Classes and Operator Overloading
Ranel Padon
 
PDF
Python Programming - XII. File Processing
Ranel Padon
 
PDF
Python Programming - XI. String Manipulation and Regular Expressions
Ranel Padon
 
PDF
Python Programming - II. The Basics
Ranel Padon
 
PDF
Python Programming - VI. Classes and Objects
Ranel Padon
 
PDF
Python Programming - XIII. GUI Programming
Ranel Padon
 
PDF
Python Programming - I. Introduction
Ranel Padon
 
Python Programming - IX. On Randomness
Ranel Padon
 
Python Programming - VIII. Inheritance and Polymorphism
Ranel Padon
 
Python Programming - III. Controlling the Flow
Ranel Padon
 
Python Programming - V. Sequences (List and Tuples) and Dictionaries
Ranel Padon
 
Switchable Map APIs with Drupal
Ranel Padon
 
Python Programming - VII. Customizing Classes and Operator Overloading
Ranel Padon
 
Python Programming - XII. File Processing
Ranel Padon
 
Python Programming - XI. String Manipulation and Regular Expressions
Ranel Padon
 
Python Programming - II. The Basics
Ranel Padon
 
Python Programming - VI. Classes and Objects
Ranel Padon
 
Python Programming - XIII. GUI Programming
Ranel Padon
 
Python Programming - I. Introduction
Ranel Padon
 
Ad

Similar to Python Programming - X. Exception Handling and Assertions (20)

PPTX
Exception handling.pptx
NISHASOMSCS113
 
PPTX
Java SE 11 Exception Handling
Ashwin Shiv
 
PDF
Control structures functions and modules in python programming
Srinivas Narasegouda
 
PPTX
Java Exceptions and Exception Handling
MaqdamYasir
 
PPTX
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
PPTX
JAVA Presenttation topics Programs.pptx
RitikSharma685066
 
PDF
Java unit 11
Shipra Swati
 
PPTX
Exception handling in java
Kavitha713564
 
PPTX
Java programming-Event Handling
Java Programming
 
PPT
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
PPTX
Exceptions overview
Bharath K
 
PPTX
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
PPTX
Exception handling in java
Elizabeth alexander
 
PDF
22 scheme OOPs with C++ BCS306B_module5.pdf
sindhus795217
 
PPT
Exception handling
zindadili
 
PPT
Exception handling
Tata Consultancy Services
 
PPTX
Week 4 - 5 Debugging Code and Analyzing Logic Errors.pptx
michael572640
 
PPTX
Exception Handling in Java
lalithambiga kamaraj
 
PDF
Introduction to Exception
Swabhav Techlabs
 
PPT
Week7 exception handling
Alpesh Oza
 
Exception handling.pptx
NISHASOMSCS113
 
Java SE 11 Exception Handling
Ashwin Shiv
 
Control structures functions and modules in python programming
Srinivas Narasegouda
 
Java Exceptions and Exception Handling
MaqdamYasir
 
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
JAVA Presenttation topics Programs.pptx
RitikSharma685066
 
Java unit 11
Shipra Swati
 
Exception handling in java
Kavitha713564
 
Java programming-Event Handling
Java Programming
 
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exceptions overview
Bharath K
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
Exception handling in java
Elizabeth alexander
 
22 scheme OOPs with C++ BCS306B_module5.pdf
sindhus795217
 
Exception handling
zindadili
 
Exception handling
Tata Consultancy Services
 
Week 4 - 5 Debugging Code and Analyzing Logic Errors.pptx
michael572640
 
Exception Handling in Java
lalithambiga kamaraj
 
Introduction to Exception
Swabhav Techlabs
 
Week7 exception handling
Alpesh Oza
 
Ad

More from Ranel Padon (9)

PDF
The Synergy of Drupal Hooks/APIs (Custom Module Development with ChartJS)
Ranel Padon
 
PDF
CKEditor Widgets with Drupal
Ranel Padon
 
PDF
Views Unlimited: Unleashing the Power of Drupal's Views Module
Ranel Padon
 
PDF
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Ranel Padon
 
PDF
PyCon PH 2014 - GeoComputation
Ranel Padon
 
PDF
Power and Elegance - Leaflet + jQuery
Ranel Padon
 
PDF
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Ranel Padon
 
PDF
Of Nodes and Maps (Web Mapping with Drupal - Part II)
Ranel Padon
 
PDF
Web Mapping with Drupal
Ranel Padon
 
The Synergy of Drupal Hooks/APIs (Custom Module Development with ChartJS)
Ranel Padon
 
CKEditor Widgets with Drupal
Ranel Padon
 
Views Unlimited: Unleashing the Power of Drupal's Views Module
Ranel Padon
 
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Ranel Padon
 
PyCon PH 2014 - GeoComputation
Ranel Padon
 
Power and Elegance - Leaflet + jQuery
Ranel Padon
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Ranel Padon
 
Of Nodes and Maps (Web Mapping with Drupal - Part II)
Ranel Padon
 
Web Mapping with Drupal
Ranel Padon
 

Recently uploaded (20)

PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Digital Circuits, important subject in CS
contactparinay1
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 

Python Programming - X. Exception Handling and Assertions