Errors are inevitable while programming — but Python gives us smart tools to handle them gracefully. In this blog, you’ll learn what exceptions are, why they occur, and how to manage them using try
, except
, and finally
blocks.
🔹 What is an Exception?
Exception is an error that occurs during the execution of a program, disrupting its normal flow. These are not syntax errors, but runtime errors such as dividing by zero or accessing an invalid index in a list.
Without proper handling, exceptions can cause the entire program to crash.
🚨 Common Exceptions in Python
- ZeroDivisionError: Raised when a number is divided by zero.
- IndexError: Occurs when trying to access an invalid list index.
- ValueError: Raised when a function gets the correct type but inappropriate value.
- TypeError: Raised when an operation is performed on incompatible types.
- KeyError: Raised when a key is not found in a dictionary.
🧰 Handling Exceptions using try - except
To prevent the program from crashing, we use try-except
blocks to catch and handle exceptions.
✅ Syntax:
try: # Code that may raise an exception except ExceptionType: # Code to handle the exception
💡 Example:
try: num = int(input("Enter a number: ")) result = 10 / num print("Result:", result) except ZeroDivisionError: print("❌ Cannot divide by zero!") except ValueError: print("❌ Invalid input. Please enter a number.")
🔄 Using finally Block
The finally
block is optional and contains code that runs no matter what — whether an exception occurred or not. It is often used to release resources like files or network connections.
✅ Syntax:
try: # risky code except: # handle error finally: # cleanup code (always runs)
💡 Example:
try: f = open("data.txt", "r") print(f.read()) except FileNotFoundError: print("❌ File not found.") finally: print("✔️ Closing file (if opened).")
🧾 Summary Table: Exception Handling Blocks
Block | Purpose |
---|---|
try | Contains code that may raise an exception |
except | Catches and handles the exception |
finally | Runs code regardless of exception (cleanup tasks) |
📝 Summary
- Exceptions are runtime errors that disrupt program execution.
try-except
blocks help handle these exceptions gracefully.finally
is used for cleanup activities and always runs.
💡 Tip: Never ignore exceptions! Handling them smartly can make your code robust and error-resilient.
Let Python throw errors — you just catch and handle them like a pro! 🧠🐍