Exception Handling in Python
By Pankaj Chouhan | Codes with Pankaj
Errors are a normal part of programming. Even experienced developers face them daily. The good news? Python gives us powerful tools to handle these errors gracefully so our programs don’t crash unexpectedly.
In this blog, you will learn exception handling in Python step by step with easy-to-understand examples.
What is an Exception?
An exception is an error that occurs while a program is running (at runtime). If not handled, it stops the program immediately.
Common Example:
a = 10
b = 0
result = a / b
print(result)Output:
ZeroDivisionError: division by zeroThe program crashes. This is not a good user experience.
The try and except Block
The basic way to handle exceptions is using try and except.
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
print("Result:", result)
except:
print("Something went wrong! Please enter valid numbers.")How it works:
- Code inside
tryis executed. - If an error occurs, the program jumps to the
exceptblock. - If no error occurs,
exceptis skipped.
Handling Specific Exceptions (Recommended)
It’s better to catch specific errors instead of a general except.
try:
num = int(input("Enter a number: "))
result = 100 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: You cannot divide by zero!")
except ValueError:
print("Error: Please enter a valid number, not text!")Some Common Exceptions:
ZeroDivisionErrorValueErrorTypeErrorFileNotFoundErrorIndexErrorKeyError
else and finally Blocks
try:
file = open("data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
else:
print("File read successfully!") # Runs only if no exception
finally:
print("This will always run - Cleanup code here")
# Close file if it was openedelse: Executes only when no exception occurs.finally: Always executes (perfect for closing files, database connections, etc.).
Example: Reading a File Safely
def read_file(filename):
try:
with open(filename, "r") as file:
data = file.read()
return data
except FileNotFoundError:
return "Error: File not found. Please check the filename."
except PermissionError:
return "Error: You don't have permission to read this file."
except Exception as e:
return f"Unexpected error: {e}"
print(read_file("students.csv"))Raising Your Own Exception
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above to register!")
print("Registration successful!")
try:
check_age(16)
except ValueError as e:
print("Error:", e)Best Practices for Exception Handling
- Always catch specific exceptions first.
- Use
finallyfor cleanup tasks. - Keep error messages user-friendly.
- Avoid using a bare
except:in production code. - Log errors (using the
loggingmodule) for debugging.
Conclusion
Exception handling makes your Python programs more robust, reliable, and user-friendly. Instead of crashing, your application can show helpful messages and continue running.
Mastering try, except, else, and finally is an essential skill for every Python developer.
Practice Exercise:
Create a simple calculator that handles division by zero and invalid input errors.
Codes with Pankaj – Making Coding Simple and Practical.
