1 Python ERROR HANDLING
1. What is Error Handling?
Error handling means dealing with mistakes in a program.
In simple words:
👉 Errors can happen
👉 Python should not crash
👉 We handle errors gracefully
2. What is an Error?
An error happens when Python cannot understand or run your code.
Examples:
-
Dividing by zero
-
Wrong data type
-
File not found
3. Common Types of Errors
| Error Name | When It Happens |
|---|---|
ZeroDivisionError |
Divide by zero |
ValueError |
Wrong value type |
TypeError |
Wrong data type |
FileNotFoundError |
File missing |
NameError |
Variable not defined |
4. Basic Error Handling (try-except)
Example
PHP
|
0 1 2 3 4 5 6 |
try: print(10 / 0) except: print("Error occurred") |
5. Handling Specific Errors
Example
PHP
|
0 1 2 3 4 5 6 |
try: num = int("abc") except ValueError: print("Please enter a number") |
6. Multiple Except Blocks
Example
PHP
|
0 1 2 3 4 5 6 |
try: x = int(input("Enter number: ")) print(10 / x) except ValueError: print("Invalid number") except ZeroDivisionError: print("Cannot divide by zero") |
7. try-except-else
else runs if no error occurs.
Example
PHP
|
0 1 2 3 4 5 6 |
try: print(10 / 2) except: print("Error") else: print("No error occurred") |
8. try-except-finally
finally runs always.
Example
PHP
|
0 1 2 3 4 5 6 |
try: print("Opening file") except: print("Error") finally: print("Program ended") |
9. Error Handling with Files
Example
PHP
|
0 1 2 3 4 5 6 |
try: file = open("data.txt", "r") print(file.read()) except FileNotFoundError: print("File not found") |
10. Raise Your Own Error
Example
PHP
|
0 1 2 3 4 5 6 |
age = -5 if age < 0: raise ValueError("Age cannot be negative") |
11. Common Beginner Mistakes
❌ Catching All Errors Without Message
PHP
|
0 1 2 3 4 5 6 |
except: pass |
👉 Not good practice.
❌ Writing Too Much Code in try
👉 Only risky code should be inside try.
12. Simple Practice Examples
Example 1: Safe Division
PHP
|
0 1 2 3 4 5 6 |
def divide(a, b): try: return a / b except ZeroDivisionError: return "Cannot divide by zero" print(divide(10, 0)) |
Example 2: Input Validation
PHP
|
0 1 2 3 4 5 6 |
try: age = int(input("Enter age: ")) print(age) except ValueError: print("Please enter a number") |
Example 3: File Read
PHP
|
0 1 2 3 4 5 6 |
try: with open("test.txt") as file: print(file.read()) except FileNotFoundError: print("File not found") |
13. Error vs Exception (Simple)
| Error | Exception |
|---|---|
| Program crash | Can be handled |
| Not controlled | Controlled using try-except |
14. Summary (Python Error Handling)
✔ Errors happen in programs
✔ Try-except prevents crash
✔ Handle specific errors
✔ Use else and finally
✔ Important for real applications
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
Custom Exceptions
-
Debugging Python Code
-
Mini Python Projects
-
Real-life Error Handling Examples
Just tell me 😊
