Python Exception Handling — Complete Notes
errors:
compile time error
logical error
runtime error
statements:
normal statements
critical statements
1. What is Exception Handling?
Definition:
Exception handling in Python is a mechanism that allows you to handle
runtime errors (exceptions) gracefully without stopping the entire program.
Purpose:
To prevent the program from crashing when an unexpected event (error)
occurs.
2. What is an Exception?
An exception is an event that occurs during the execution of a program and
disrupts the normal flow of instructions.
Common Examples:
Exception TypeDescription
ZeroDivisionErrorDivision by zero
TypeError Operation on an inappropriate type
ValueError Invalid value used
FileNotFoundError
File not found on disk
IndexError Index out of range in a list
KeyError Key not found in a dictionary
Exception TypeDescription
NameError Variable not defined
ImportError Module not found or cannot be imported
3. Basic Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle that exception
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
Output:
You cannot divide by zero!