Lecture 7-8 Exception Handling-1
Lecture 7-8 Exception Handling-1
Exceptions
• Exceptions are unforeseen errors or problems that can occur during
the execution of a Python program.
• These errors can cause the program to terminate abruptly if not
handled properly. Python provides a robust mechanism called
"exception handling" to manage such errors gracefully.
ZeroDivisionError, IndexError,
TypeError, KeyError,
ValueError, NameError
IOError,
ZeroDivisionError,
TypeError,
ValueError,
Types of
IOError,
Exception
IndexError,
KeyError,
NameError
Example of Exception
• 102/0 ZeroDivisionError
• Int(“Hello”) TypeError
• date_str = "2023-07-32"
ValueError
• date_obj = datetime.strptime(date_str, "%Y-%m-
%d")
Try and Except Statement
• Try and except statements are used to catch and handle exceptions in
Python.
• Statements that can raise exceptions are kept inside the try clause
and the statements that handle the exception are written inside
except clause.
Handling Exception
Find Exception type
ZeroDivisionError: This exception is raised when an attempt is made to
divide a number by zero.
num = int(input("Enter a number: "))
result = 10 / num
TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type.