python Exception Handling That Fixes Problems
Exception Handling That Fixes Problems
Beginner Mindset vs Professional Mindset
Many beginners write exception handling like this:
try:
risky_code()
except:
print("Error")
This catches an error and displays a message.
However, professional exception handling goes much further.
The goal is not merely to detect errors.
The goal is often to:
- Recover from the error
- Repair invalid data
- Retry failed operations
- Use safe defaults
- Continue program execution
- Improve user experience
What Can an Exception Handler Do?
Instead of only reporting errors, an except block can:
| Recovery Action | Description |
|---|---|
| Correct Invalid Data | Replace bad values with valid ones |
| Use Default Values | Provide fallback values |
| Retry Operations | Try again after failure |
| Create Missing Files | Generate required resources |
| Reconnect to Servers | Restore lost connections |
| Ask for Input Again | Let the user retry |
| Recover From Failures | Continue execution safely |
Traditional Error Handling
Error Occurs
↓
Print Error
↓
Program Stops
Example:
try:
age = int(input("Enter age: "))
except ValueError:
print("Invalid input")
Output:
Enter age: abc
Invalid input
Program may continue, but the problem is not fixed.
Recovery-Based Error Handling
Error Occurs
↓
Detect Error
↓
Repair Problem
↓
Continue Program
This is much more useful in real-world applications.
Example 1: Fix Invalid User Input
Without Recovery
try:
age = int(input("Enter age: "))
except ValueError:
print("Invalid input")
Output:
Enter age: abc
Invalid input
Problem:
Age value is still unavailable.
Improved Version
try:
age = int(input("Enter age: "))
except ValueError:
print("Invalid input.")
age = 18
print("Using default age:", age)
print("Program continues...")
Output:
Enter age: abc
Invalid input.
Using default age: 18
Program continues...
What Happened?
User entered invalid data
↓
ValueError occurred
↓
Default value assigned
↓
Program continued safely
The exception handler fixed the problem.
Example 2: Automatically Create Missing File
A missing file should not always crash the program.
Recovery Solution
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File missing. Creating it...")
file = open("data.txt", "w")
file.write("Default Content")
file.close()
file = open("data.txt", "r")
print(file.read())
file.close()
Output:
File missing. Creating it...
Default Content
Recovery Flow
File Not Found
↓
FileNotFoundError
↓
Create File
↓
Open File Again
↓
Continue Program
The exception handler repaired the issue.
Example 3: Retry Until Correct Input
One of the most common real-world recovery techniques is retrying.
Program
while True:
try:
number = int(input("Enter Number: "))
break
except ValueError:
print("Numbers only. Try again.")
print("You entered:", number)
Output
Enter Number: abc
Numbers only. Try again.
Enter Number: xyz
Numbers only. Try again.
Enter Number: 50
You entered: 50
Recovery Flow
Invalid Input
↓
ValueError
↓
Ask Again
↓
Ask Again
↓
Valid Input
↓
Continue
This pattern is used in:
- Login systems
- ATM machines
- Registration forms
- Banking software
- Payment systems
Example 4: Recover From Division By Zero
Instead of crashing when the divisor is zero, we can automatically replace it.
Program
try:
denominator = int(input("Enter divisor: "))
result = 100 / denominator
except ZeroDivisionError:
print("Cannot divide by zero.")
denominator = 1
result = 100 / denominator
print(result)
Output
Enter divisor: 0
Cannot divide by zero.
100.0
Recovery Flow
Divisor = 0
↓
ZeroDivisionError
↓
Replace Divisor With 1
↓
Recalculate Result
↓
Continue
The exception handler automatically corrected the divisor.
Example 5: Dictionary Recovery
Missing dictionary keys are very common.
Instead of failing, we can create the missing data.
Program
student = {
"name": "John"
}
try:
age = student["age"]
except KeyError:
print("Age not found.")
student["age"] = 18
age = student["age"]
print(age)
Output
Age not found.
18
Recovery Flow
Missing Key
↓
KeyError
↓
Create Key
↓
Assign Default Value
↓
Continue
The exception handler repaired the data structure.
Example 6: Automatic Reconnection
Real-world applications often reconnect automatically.
try:
connect_to_server()
except ConnectionError:
print("Reconnecting...")
connect_to_server()
Flow:
Connection Lost
↓
ConnectionError
↓
Reconnect
↓
Continue
Used in:
- Games
- Banking apps
- Mobile apps
- Web applications
Example 7: Recover From Missing Configuration
try:
file = open("config.txt")
except FileNotFoundError:
print("Creating default configuration")
file = open("config.txt", "w")
file.write("theme=light")
Flow:
Config Missing
↓
Create Default Config
↓
Continue
Recovery Strategies Used by Professionals
Strategy 1: Use Default Values
except ValueError:
age = 18
Strategy 2: Retry
except ValueError:
continue
Strategy 3: Reconnect
except ConnectionError:
reconnect()
Strategy 4: Create Missing Resources
except FileNotFoundError:
create_file()
Strategy 5: Repair Data
except KeyError:
dictionary["key"] = default_value
When NOT to Recover
Sometimes recovery is unsafe.
Example:
try:
withdraw_money()
except Exception:
pass
Bad idea.
A banking transaction should never silently ignore errors.
Instead:
try:
withdraw_money()
except Exception as error:
log_error(error)
raise
Some errors must stop execution.
Real-World Rule
A professional developer usually follows this principle:
Try to PREVENT errors first.
If prevention is impossible,
use exceptions to RECOVER.
Only show error messages
when recovery isn't possible.
Good Exception Handling
Error Occurs
↓
Detect Error
↓
Fix Problem
↓
Continue Program
Examples:
✓ Assign default values
✓ Retry operations
✓ Create files
✓ Reconnect servers
✓ Repair data
✓ Ask user again
Poor Exception Handling
Error Occurs
↓
Print Error
↓
Crash
or even worse:
Error Occurs
↓
Ignore Error
↓
Corrupt Program State
Common Beginner Mistakes
Mistake 1
except:
print("Error")
Too generic.
Mistake 2
except:
pass
Silently hides problems.
Mistake 3
except ValueError:
print("Wrong value")
Only reporting the problem without fixing it.
Mistake 4
Not providing fallback values.
Example:
except ValueError:
pass
Now the variable may not exist later.
Best Practices
✅ Catch specific exceptions
✅ Recover when possible
✅ Use sensible defaults
✅ Retry temporary failures
✅ Log important errors
✅ Keep programs running safely
✅ Stop execution when recovery is unsafe
Summary
Exception handling is not only about catching errors.
A good exception handler should attempt to:
- Detect the error
- Understand the cause
- Repair the problem if possible
- Continue execution safely
Professional software rarely uses exceptions just to display messages.
Instead, exceptions are often used as a recovery mechanism that keeps applications running smoothly even when unexpected problems occur.