💡 Introduction to Exception Handling
In Python, exceptions are errors that occur during the execution of a program.
When an error occurs, Python stops the normal flow of the program and raises an exception.
👉 Exception handling allows you to handle these errors gracefully — without crashing the
program.
Common examples of exceptions:
ZeroDivisionError – dividing by zero
ValueError – wrong type of value
FileNotFoundError – file doesn’t exist
IndexError – accessing an invalid index in a list
🧩 Syntax of Exception Handling
try:
# Code that might cause an exception
except ExceptionType:
# Code that runs if an exception occurs
finally:
# Code that always runs (optional)
⚙️Using try-except
The try block contains the code that might raise an exception.
The except block handles the error.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input, please enter a number.")
✅ Output Example:
Enter a number: 0
Error: Cannot divide by zero!
🧱 Using finally
The finally block is always executed, whether an exception occurs or not.
It is often used to release resources (like closing a file or database connection).
Example:
try:
file = open("[Link]", "r")
content = [Link]()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
[Link]()
print("File closed.")
✅ Output Example:
File not found!
File closed.
✅ Summary
Block Purpose
try Contains code that may raise an exception
except Handles the exception
finall Always executes (cleanup code)
y