SlideShare a Scribd company logo
Exceptions
Team Emertxe
Introduction
Errors
ļ¬
Categories of Errors
ļ¬
Compile-time
ļ¬
Runtime
ļ¬
Logical
Errors
Compile-Time
What? These are syntactical errors found in the code, due to which program
fails to compile
Example Missing a colon in the statements llike if, while, for, def etc
Program Output
x = 1
if x == 1
print("Colon missing")
py 1.0_compile_time_error.py
File "1.0_compile_time_error.py", line 5
if x == 1
^
SyntaxError: invalid syntax
x = 1
#Indentation Error
if x == 1:
print("Hai")
print("Hello")
py 1.1_compile_time_error.py
File "1.1_compile_time_error.py", line 8
print("Hello")
^
IndentationError: unexpected indent
Errors
Runtime - 1
What? When PVM cannot execute the byte code, it flags runtime error
Example Insufficient memory to store something or inability of the PVM to
execute some statement come under runtime errors
Program Output
def combine(a, b):
print(a + b)
#Call the combine function
combine("Hai", 25)
py 2.0_runtime_errors.py
Traceback (most recent call last):
File "2.0_runtime_errors.py", line 7, in <module>
combine("Hai", 25)
File "2.0_runtime_errors.py", line 4, in combine
print(a + b)
TypeError: can only concatenate str (not "int") to str
"""
Conclusion:
1. Compiler will not check the datatypes.
2.Type checking is done by PVM during run-time.
"""
Errors
Runtime - 2
What? When PVM cannot execute the byte code, it flags runtime error
Example Insufficient memory to store something or inability of the PVM to
execute some statement come under runtime errors
Program Output
#Accessing the item beyond the array
bounds
lst = ["A", "B", "C"]
print(lst[3])
py 2.1_runtime_errors.py
Traceback (most recent call last):
File "2.1_runtime_errors.py", line 5, in <module>
print(lst[3])
IndexError: list index out of range
Errors
Logical-1
What? These errors depicts flaws in the logic of the program
Example Usage of wrong formulas
Program Output
def increment(sal):
sal = sal * 15 / 100
return sal
#Call the increment()
sal = increment(5000.00)
print("New Salary: %.2f" % sal)
py 3.0_logical_errors.py
New Salary: 750.00
Errors
Logical-2
What? These errors depicts flaws in the logic of the program
Example Usage of wrong formulas
Program Output
#1. Open the file
f = open("myfile", "w")
#Accept a, b, store the result of a/b into the file
a, b = [int(x) for x in input("Enter two number: ").split()]
c = a / b
#Write the result into the file
f.write("Writing %d into myfile" % c)
#Close the file
f.close()
print("File closed")
py 4_effect_of_exception.py
Enter two number: 10 0
Traceback (most recent call last):
File "4_effect_of_exception.py", line 8, in
<module>
c = a / b
ZeroDivisionError: division by zero
Errors
Common
ļ¬
When there is an error in a program, due to its sudden termination, the following things
can be suspected
ļ¬
The important data in the files or databases used in the program may be lost
ļ¬
The software may be corrupted
ļ¬
The program abruptly terminates giving error message to the user making the user
losing trust in the software
Exceptions
Introduction
ļ¬
An exception is a runtime error which can be handled by the programmer
ļ¬
The programmer can guess an error and he can do something to eliminate the harm caused by
that error called an ā€˜Exceptionā€™
BaseException
Exception
StandardError Warning
ArthmeticError
AssertionError
SyntaxError
TypeError
EOFError
RuntimeError
ImportError
NameError
DeprecationWarning
RuntimeWarning
ImportantWarning
Exceptions
Exception Handling
ļ¬
The purpose of handling errors is to make program robust
Step-1 try:
statements
#To handle the ZeroDivisionError Exception
try:
f = open("myfile", "w")
a, b = [int(x) for x in input("Enter two numbers: ").split()]
c = a / b
f.write("Writing %d into myfile" % c)
Step-2 except exeptionname:
statements
except ZeroDivisionError:
print("Divide by Zero Error")
print("Don't enter zero as input")
Step-3 finally:
statements
finally:
f.close()
print("Myfile closed")
Exceptions
Program
#To handle the ZeroDivisionError Exception
#An Exception handling Example
try:
f = open("myfile", "w")
a, b = [int(x) for x in input("Enter two numbers: ").split()]
c = a / b
f.write("Writing %d into myfile" % c)
except ZeroDivisionError:
print("Divide by Zero Error")
print("Don't enter zero as input")
finally:
f.close()
print("Myfile closed")
Output:
py 5_exception_handling.py
Enter two numbers: 10 0
Divide by Zero Error
Don't enter zero as input
Myfile closed
Exceptions
Exception Handling Syntax
try:
statements
except Exception1:
handler1
except Exception2:
handler2
else:
statements
finally:
statements
Exceptions
Exception Handling: Noteworthy
- A single try block can contain several except blocks.
- Multiple except blocks can be used to handle multiple exceptions.
- We cannot have except block without the try block.
- We can write try block without any except block.
- Else and finally are not compulsory.
- When there is no exception, else block is executed after the try block.
- Finally block is always executed.
Exceptions
Types: Program-1
#To handle the syntax error given by eval() function
#Example for Synatx error
try:
date = eval(input("Enter the date: "))
except SyntaxError:
print("Invalid Date")
else:
print("You entered: ", date)
Output:
Run-1:
Enter the date: 5, 12, 2018
You entered: (5, 12, 2018)
Run-2:
Enter the date: 5d, 12m, 2018y
Invalid Date
Exceptions
Types: Program-2
#To handle the IOError by open() function
#Example for IOError
try:
name = input("Enter the filename: ")
f = open(name, "r")
except IOError:
print("File not found: ", name)
else:
n = len(f.readlines())
print(name, "has", n, "Lines")
f.close()
If the entered file is not exists, it will raise an IOError
Exceptions
Types: Program-3
#Example for two exceptions
#A function to find the total and average of list elements
def avg(list):
tot = 0
for x in list:
tot += x
avg = tot / len(list)
return tot.avg
#Call avg() and pass the list
try:
t, a = avg([1, 2, 3, 4, 5, 'a'])
#t, a = avg([]) #Will give ZeroDivisionError
print("Total = {}, Average = {}". format(t, a))
except TypeError:
print("Type Error: Pls provide the numbers")
except ZeroDivisionError:
print("ZeroDivisionError, Pls do not give empty list")
Output:
Run-1:
Type Error: Pls provide the numbers
Run-2:
ZeroDivisionError, Pls do not give empty list
Exceptions
Except Block: Various formats
Format-1 except Exceptionclass:
Format-2 except Exceptionclass as obj:
Format-3 except (Exceptionclass1, Exceptionclass2, ...):
Format-4 except:
Exceptions
Types: Program-3A
#Example for two exceptions
#A function to find the total and average of list elements
def avg(list):
tot = 0
for x in list:
tot += x
avg = tot / len(list)
return tot.avg
#Call avg() and pass the list
try:
t, a = avg([1, 2, 3, 4, 5, 'a'])
#t, a = avg([]) #Will give ZeroDivisionError
print("Total = {}, Average = {}". format(t, a))
except (TypeError, ZeroDivisionError):
print("Type Error / ZeroDivisionErrorā€)
Output:
Run-1:
Type Error / ZeroDivisionError
Run-2:
Type Error / ZeroDivisionError
Exceptions
The assert Statement
ļ¬
It is useful to ensure that a given condition is True, It is not True, it raises
AssertionError.
ļ¬
Syntax:
assert condition, message
Exceptions
The assert Statement: Programs
Program - 1 Program - 2
#Handling AssertionError
try:
x = int(input("Enter the number between 5 and 10: "))
assert x >= 5 and x <= 10
print("The number entered: ", x)
except AssertionError:
print("The condition is not fulfilled")
#Handling AssertionError
try:
x = int(input("Enter the number between 5 and 10: "))
assert x >= 5 and x <= 10, "Your input is INVALID"
print("The number entered: ", x)
except AssertionError as Obj:
print(Obj)
Exceptions
User-Defined Exceptions
Step-1 class MyException(Exception):
def __init__(self, arg):
self.msg = arg
Step-2 raise MyException("Message")
Step-3 try:
#code
except MyException as me:
print(me)
Exceptions
User-Defined Exceptions: Program
#To create our own exceptions and raise it when needed
class MyException(Exception):
def __init__(self, arg):
self.msg = arg
def check(dict):
for k, v in dict.items():
print("Name = {:15s} Balance = {:10.2f}" . format(k, v)) if (v < 2000.00):
raise MyException("Less Bal Amount" + k)
bank = {"Raj": 5000.00, "Vani": 8900.50, "Ajay": 1990.00}
try:
check(bank)
except MyException as me:
print(me)
THANK YOU

More Related Content

What's hot

Exception handling in Python
Exception handling in PythonException handling in Python
Exception handling in Python
Adnan Siddiqi
Ā 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
Ā 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
Ā 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
Ā 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
Ā 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
Ā 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
P3 InfoTech Solutions Pvt. Ltd.
Ā 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
Ā 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
Ā 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
Ā 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Python : Functions
Python : FunctionsPython : Functions
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
Sujith Kumar
Ā 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
Ā 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
baabtra.com - No. 1 supplier of quality freshers
Ā 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
Ā 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
Ā 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
Ā 
Operators in python
Operators in pythonOperators in python
Operators in python
Prabhakaran V M
Ā 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Kamal Acharya
Ā 

What's hot (20)

Exception handling in Python
Exception handling in PythonException handling in Python
Exception handling in Python
Ā 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Ā 
Exception Handling
Exception HandlingException Handling
Exception Handling
Ā 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
Ā 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
Ā 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Ā 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
Ā 
Python Modules
Python ModulesPython Modules
Python Modules
Ā 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Ā 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Ā 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
Ā 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Ā 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
Ā 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Ā 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
Ā 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
Ā 
Functions in python
Functions in pythonFunctions in python
Functions in python
Ā 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Ā 
Operators in python
Operators in pythonOperators in python
Operators in python
Ā 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Ā 

Similar to Python programming : Exceptions

Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
junnubabu
Ā 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
Inzamam Baig
Ā 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
Vivek chan
Ā 
Python Session - 6
Python Session - 6Python Session - 6
Python Session - 6
AnirudhaGaikwad4
Ā 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
Ā 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
sarthakgithub
Ā 
Exception handling
Exception handlingException handling
Exception handling
Waqas Abbasi
Ā 
TYPES OF ERRORS.pptx
TYPES OF ERRORS.pptxTYPES OF ERRORS.pptx
TYPES OF ERRORS.pptx
muskanaggarwal84101
Ā 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
wulanpermatasari27
Ā 
C and its errors
C and its errorsC and its errors
C and its errorsJunaid Raja
Ā 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
Ā 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
Vinod Srivastava
Ā 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
mustafatahertotanawa1
Ā 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
Syed Bahadur Shah
Ā 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
Ā 
embeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptxembeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptx
sangeetaSS
Ā 
Embedded C - Lecture 1
Embedded C - Lecture 1Embedded C - Lecture 1
Embedded C - Lecture 1
Mohamed Abdallah
Ā 
Unit iii
Unit iiiUnit iii
Unit iii
snehaarao19
Ā 
exceptioninpython.pptx
exceptioninpython.pptxexceptioninpython.pptx
exceptioninpython.pptx
SulekhJangra
Ā 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
VGaneshKarthikeyan
Ā 

Similar to Python programming : Exceptions (20)

Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
Ā 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
Ā 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
Ā 
Python Session - 6
Python Session - 6Python Session - 6
Python Session - 6
Ā 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
Ā 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
Ā 
Exception handling
Exception handlingException handling
Exception handling
Ā 
TYPES OF ERRORS.pptx
TYPES OF ERRORS.pptxTYPES OF ERRORS.pptx
TYPES OF ERRORS.pptx
Ā 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
Ā 
C and its errors
C and its errorsC and its errors
C and its errors
Ā 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Ā 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
Ā 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
Ā 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
Ā 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
Ā 
embeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptxembeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptx
Ā 
Embedded C - Lecture 1
Embedded C - Lecture 1Embedded C - Lecture 1
Embedded C - Lecture 1
Ā 
Unit iii
Unit iiiUnit iii
Unit iii
Ā 
exceptioninpython.pptx
exceptioninpython.pptxexceptioninpython.pptx
exceptioninpython.pptx
Ā 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
Ā 

More from Emertxe Information Technologies Pvt Ltd

Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
Emertxe Information Technologies Pvt Ltd
Ā 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf
01_student_record.pdf
01_student_record.pdf01_student_record.pdf
07_product_matrix.pdf
07_product_matrix.pdf07_product_matrix.pdf
01_memory_manager.pdf
01_memory_manager.pdf01_memory_manager.pdf

More from Emertxe Information Technologies Pvt Ltd (20)

premium post (1).pdf
premium post (1).pdfpremium post (1).pdf
premium post (1).pdf
Ā 
Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
Ā 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf
10_isxdigit.pdf
Ā 
01_student_record.pdf
01_student_record.pdf01_student_record.pdf
01_student_record.pdf
Ā 
02_swap.pdf
02_swap.pdf02_swap.pdf
02_swap.pdf
Ā 
01_sizeof.pdf
01_sizeof.pdf01_sizeof.pdf
01_sizeof.pdf
Ā 
07_product_matrix.pdf
07_product_matrix.pdf07_product_matrix.pdf
07_product_matrix.pdf
Ā 
06_sort_names.pdf
06_sort_names.pdf06_sort_names.pdf
06_sort_names.pdf
Ā 
05_fragments.pdf
05_fragments.pdf05_fragments.pdf
05_fragments.pdf
Ā 
04_magic_square.pdf
04_magic_square.pdf04_magic_square.pdf
04_magic_square.pdf
Ā 
03_endianess.pdf
03_endianess.pdf03_endianess.pdf
03_endianess.pdf
Ā 
02_variance.pdf
02_variance.pdf02_variance.pdf
02_variance.pdf
Ā 
01_memory_manager.pdf
01_memory_manager.pdf01_memory_manager.pdf
01_memory_manager.pdf
Ā 
09_nrps.pdf
09_nrps.pdf09_nrps.pdf
09_nrps.pdf
Ā 
11_pangram.pdf
11_pangram.pdf11_pangram.pdf
11_pangram.pdf
Ā 
10_combinations.pdf
10_combinations.pdf10_combinations.pdf
10_combinations.pdf
Ā 
08_squeeze.pdf
08_squeeze.pdf08_squeeze.pdf
08_squeeze.pdf
Ā 
07_strtok.pdf
07_strtok.pdf07_strtok.pdf
07_strtok.pdf
Ā 
06_reverserec.pdf
06_reverserec.pdf06_reverserec.pdf
06_reverserec.pdf
Ā 
05_reverseiter.pdf
05_reverseiter.pdf05_reverseiter.pdf
05_reverseiter.pdf
Ā 

Recently uploaded

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
Ā 
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
UiPathCommunity
Ā 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
Ā 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
Ā 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
Ā 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
Ā 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
Ā 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
Ā 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
Ā 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
Ā 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
Ā 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
Ā 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
Ā 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
Ā 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
Ā 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
Ā 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
Ā 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
Ā 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
Ā 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
Ā 

Recently uploaded (20)

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
Ā 
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Ā 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
Ā 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Ā 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Ā 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Ā 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Ā 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Ā 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Ā 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Ā 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Ā 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Ā 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Ā 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
Ā 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Ā 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ā 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Ā 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
Ā 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
Ā 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
Ā 

Python programming : Exceptions

  • 4. Errors Compile-Time What? These are syntactical errors found in the code, due to which program fails to compile Example Missing a colon in the statements llike if, while, for, def etc Program Output x = 1 if x == 1 print("Colon missing") py 1.0_compile_time_error.py File "1.0_compile_time_error.py", line 5 if x == 1 ^ SyntaxError: invalid syntax x = 1 #Indentation Error if x == 1: print("Hai") print("Hello") py 1.1_compile_time_error.py File "1.1_compile_time_error.py", line 8 print("Hello") ^ IndentationError: unexpected indent
  • 5. Errors Runtime - 1 What? When PVM cannot execute the byte code, it flags runtime error Example Insufficient memory to store something or inability of the PVM to execute some statement come under runtime errors Program Output def combine(a, b): print(a + b) #Call the combine function combine("Hai", 25) py 2.0_runtime_errors.py Traceback (most recent call last): File "2.0_runtime_errors.py", line 7, in <module> combine("Hai", 25) File "2.0_runtime_errors.py", line 4, in combine print(a + b) TypeError: can only concatenate str (not "int") to str """ Conclusion: 1. Compiler will not check the datatypes. 2.Type checking is done by PVM during run-time. """
  • 6. Errors Runtime - 2 What? When PVM cannot execute the byte code, it flags runtime error Example Insufficient memory to store something or inability of the PVM to execute some statement come under runtime errors Program Output #Accessing the item beyond the array bounds lst = ["A", "B", "C"] print(lst[3]) py 2.1_runtime_errors.py Traceback (most recent call last): File "2.1_runtime_errors.py", line 5, in <module> print(lst[3]) IndexError: list index out of range
  • 7. Errors Logical-1 What? These errors depicts flaws in the logic of the program Example Usage of wrong formulas Program Output def increment(sal): sal = sal * 15 / 100 return sal #Call the increment() sal = increment(5000.00) print("New Salary: %.2f" % sal) py 3.0_logical_errors.py New Salary: 750.00
  • 8. Errors Logical-2 What? These errors depicts flaws in the logic of the program Example Usage of wrong formulas Program Output #1. Open the file f = open("myfile", "w") #Accept a, b, store the result of a/b into the file a, b = [int(x) for x in input("Enter two number: ").split()] c = a / b #Write the result into the file f.write("Writing %d into myfile" % c) #Close the file f.close() print("File closed") py 4_effect_of_exception.py Enter two number: 10 0 Traceback (most recent call last): File "4_effect_of_exception.py", line 8, in <module> c = a / b ZeroDivisionError: division by zero
  • 9. Errors Common ļ¬ When there is an error in a program, due to its sudden termination, the following things can be suspected ļ¬ The important data in the files or databases used in the program may be lost ļ¬ The software may be corrupted ļ¬ The program abruptly terminates giving error message to the user making the user losing trust in the software
  • 10. Exceptions Introduction ļ¬ An exception is a runtime error which can be handled by the programmer ļ¬ The programmer can guess an error and he can do something to eliminate the harm caused by that error called an ā€˜Exceptionā€™ BaseException Exception StandardError Warning ArthmeticError AssertionError SyntaxError TypeError EOFError RuntimeError ImportError NameError DeprecationWarning RuntimeWarning ImportantWarning
  • 11. Exceptions Exception Handling ļ¬ The purpose of handling errors is to make program robust Step-1 try: statements #To handle the ZeroDivisionError Exception try: f = open("myfile", "w") a, b = [int(x) for x in input("Enter two numbers: ").split()] c = a / b f.write("Writing %d into myfile" % c) Step-2 except exeptionname: statements except ZeroDivisionError: print("Divide by Zero Error") print("Don't enter zero as input") Step-3 finally: statements finally: f.close() print("Myfile closed")
  • 12. Exceptions Program #To handle the ZeroDivisionError Exception #An Exception handling Example try: f = open("myfile", "w") a, b = [int(x) for x in input("Enter two numbers: ").split()] c = a / b f.write("Writing %d into myfile" % c) except ZeroDivisionError: print("Divide by Zero Error") print("Don't enter zero as input") finally: f.close() print("Myfile closed") Output: py 5_exception_handling.py Enter two numbers: 10 0 Divide by Zero Error Don't enter zero as input Myfile closed
  • 13. Exceptions Exception Handling Syntax try: statements except Exception1: handler1 except Exception2: handler2 else: statements finally: statements
  • 14. Exceptions Exception Handling: Noteworthy - A single try block can contain several except blocks. - Multiple except blocks can be used to handle multiple exceptions. - We cannot have except block without the try block. - We can write try block without any except block. - Else and finally are not compulsory. - When there is no exception, else block is executed after the try block. - Finally block is always executed.
  • 15. Exceptions Types: Program-1 #To handle the syntax error given by eval() function #Example for Synatx error try: date = eval(input("Enter the date: ")) except SyntaxError: print("Invalid Date") else: print("You entered: ", date) Output: Run-1: Enter the date: 5, 12, 2018 You entered: (5, 12, 2018) Run-2: Enter the date: 5d, 12m, 2018y Invalid Date
  • 16. Exceptions Types: Program-2 #To handle the IOError by open() function #Example for IOError try: name = input("Enter the filename: ") f = open(name, "r") except IOError: print("File not found: ", name) else: n = len(f.readlines()) print(name, "has", n, "Lines") f.close() If the entered file is not exists, it will raise an IOError
  • 17. Exceptions Types: Program-3 #Example for two exceptions #A function to find the total and average of list elements def avg(list): tot = 0 for x in list: tot += x avg = tot / len(list) return tot.avg #Call avg() and pass the list try: t, a = avg([1, 2, 3, 4, 5, 'a']) #t, a = avg([]) #Will give ZeroDivisionError print("Total = {}, Average = {}". format(t, a)) except TypeError: print("Type Error: Pls provide the numbers") except ZeroDivisionError: print("ZeroDivisionError, Pls do not give empty list") Output: Run-1: Type Error: Pls provide the numbers Run-2: ZeroDivisionError, Pls do not give empty list
  • 18. Exceptions Except Block: Various formats Format-1 except Exceptionclass: Format-2 except Exceptionclass as obj: Format-3 except (Exceptionclass1, Exceptionclass2, ...): Format-4 except:
  • 19. Exceptions Types: Program-3A #Example for two exceptions #A function to find the total and average of list elements def avg(list): tot = 0 for x in list: tot += x avg = tot / len(list) return tot.avg #Call avg() and pass the list try: t, a = avg([1, 2, 3, 4, 5, 'a']) #t, a = avg([]) #Will give ZeroDivisionError print("Total = {}, Average = {}". format(t, a)) except (TypeError, ZeroDivisionError): print("Type Error / ZeroDivisionErrorā€) Output: Run-1: Type Error / ZeroDivisionError Run-2: Type Error / ZeroDivisionError
  • 20. Exceptions The assert Statement ļ¬ It is useful to ensure that a given condition is True, It is not True, it raises AssertionError. ļ¬ Syntax: assert condition, message
  • 21. Exceptions The assert Statement: Programs Program - 1 Program - 2 #Handling AssertionError try: x = int(input("Enter the number between 5 and 10: ")) assert x >= 5 and x <= 10 print("The number entered: ", x) except AssertionError: print("The condition is not fulfilled") #Handling AssertionError try: x = int(input("Enter the number between 5 and 10: ")) assert x >= 5 and x <= 10, "Your input is INVALID" print("The number entered: ", x) except AssertionError as Obj: print(Obj)
  • 22. Exceptions User-Defined Exceptions Step-1 class MyException(Exception): def __init__(self, arg): self.msg = arg Step-2 raise MyException("Message") Step-3 try: #code except MyException as me: print(me)
  • 23. Exceptions User-Defined Exceptions: Program #To create our own exceptions and raise it when needed class MyException(Exception): def __init__(self, arg): self.msg = arg def check(dict): for k, v in dict.items(): print("Name = {:15s} Balance = {:10.2f}" . format(k, v)) if (v < 2000.00): raise MyException("Less Bal Amount" + k) bank = {"Raj": 5000.00, "Vani": 8900.50, "Ajay": 1990.00} try: check(bank) except MyException as me: print(me)