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

PDF
Constructors and Destructors
Dr Sukhpal Singh Gill
 
PPTX
File handling in c
aakanksha s
 
PDF
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
PPTX
Chapter 05 classes and objects
Praveen M Jigajinni
 
PDF
File handling in Python
BMS Institute of Technology and Management
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
PPT
structure and union
student
 
PPTX
Python dictionary
Mohammed Sikander
 
PPTX
Modules in Python Programming
sambitmandal
 
PPTX
File handling in Python
Megha V
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PDF
Python Flow Control
Mohammed Sikander
 
PDF
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
PDF
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
PDF
Control Structures in Python
Sumit Satam
 
PPTX
Functions in python
colorsof
 
PPTX
python conditional statement.pptx
Dolchandra
 
PPTX
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
PPTX
Exception handling c++
Jayant Dalvi
 
Constructors and Destructors
Dr Sukhpal Singh Gill
 
File handling in c
aakanksha s
 
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Chapter 05 classes and objects
Praveen M Jigajinni
 
Python functions
Prof. Dr. K. Adisesha
 
structure and union
student
 
Python dictionary
Mohammed Sikander
 
Modules in Python Programming
sambitmandal
 
File handling in Python
Megha V
 
Python: Modules and Packages
Damian T. Gordon
 
Python Flow Control
Mohammed Sikander
 
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Control Structures in Python
Sumit Satam
 
Functions in python
colorsof
 
python conditional statement.pptx
Dolchandra
 
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
Exception handling c++
Jayant Dalvi
 

Similar to Python programming : Exceptions (20)

PPTX
Exception Handling in python programming.pptx
shririshsri
 
PPTX
Error and exception in python
junnubabu
 
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
PPTX
EXCEPTIONS-PYTHON.pptx RUNTIME ERRORS HANDLING
NagarathnaRajur2
 
PPTX
Download Wondershare Filmora Crack Latest 2025
hyderik195
 
PPTX
Adobe Photoshop 2025 Cracked Latest Version
hyderik195
 
PPTX
FL Studio Producer Edition Crack 24 + Latest Version [2025]
hyderik195
 
PPTX
Exception Handling in Python Programming.pptx
vinayagrawal71
 
PPTX
Exception handling with python class 12.pptx
PreeTVithule1
 
PPTX
Python Lecture 7
Inzamam Baig
 
PDF
Unit 4-Exception Handling in Python.pdf
Harsha Patil
 
PPTX
Exception Handling.pptx
Pavan326406
 
PDF
Exception handling in python
Lifna C.S
 
PPTX
Exception handling.pptx
NISHASOMSCS113
 
PPTX
Exception handling.pptxnn h
sabarivelan111007
 
PPTX
Exception Handling in Python topic .pptx
mitu4846t
 
PPTX
Chapter 13 exceptional handling
Praveen M Jigajinni
 
PPTX
Exception Handling in Python
DrJasmineBeulahG
 
PPT
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
Exception Handling in python programming.pptx
shririshsri
 
Error and exception in python
junnubabu
 
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
EXCEPTIONS-PYTHON.pptx RUNTIME ERRORS HANDLING
NagarathnaRajur2
 
Download Wondershare Filmora Crack Latest 2025
hyderik195
 
Adobe Photoshop 2025 Cracked Latest Version
hyderik195
 
FL Studio Producer Edition Crack 24 + Latest Version [2025]
hyderik195
 
Exception Handling in Python Programming.pptx
vinayagrawal71
 
Exception handling with python class 12.pptx
PreeTVithule1
 
Python Lecture 7
Inzamam Baig
 
Unit 4-Exception Handling in Python.pdf
Harsha Patil
 
Exception Handling.pptx
Pavan326406
 
Exception handling in python
Lifna C.S
 
Exception handling.pptx
NISHASOMSCS113
 
Exception handling.pptxnn h
sabarivelan111007
 
Exception Handling in Python topic .pptx
mitu4846t
 
Chapter 13 exceptional handling
Praveen M Jigajinni
 
Exception Handling in Python
DrJasmineBeulahG
 
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
Ad

More from Emertxe Information Technologies Pvt Ltd (20)

Ad

Recently uploaded (20)

PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PDF
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
PPTX
The birth and death of Stars - earth and life science
rizellemarieastrolo
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
Kubernetes - Architecture & Components.pdf
geethak285
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
The birth and death of Stars - earth and life science
rizellemarieastrolo
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 

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)