Adding Error Handling
Input validation catches predictable problems. Error handling catches everything else — unexpected situations that might otherwise crash your program. Robust software anticipates failure and responds gracefully.
The Difference From Validation
Validation checks input before processing: "Is this a valid binary string?"
Error handling catches problems during processing: "Something went wrong while converting — what now?"
Both work together to create reliable software.
Wrapping Risky Operations
Any operation that might fail should be wrapped in try/except. Here's a safer conversion function:
def safe_convert(value, from_base, to_base):
"""Convert a number between bases with error handling."""
try:
# First convert to decimal
decimal = int(value, from_base)
# Then convert to target base
if to_base == 2:
return bin(decimal)[2:]
elif to_base == 8:
return oct(decimal)[2:]
elif to_base == 16:
return hex(decimal)[2:].upper()
else:
return str(decimal)
except ValueError as e:
return f"Error: Invalid input - {e}"
except Exception as e:
return f"Unexpected error: {e}"
This function catches ValueError specifically (the most likely problem) and has a general Exception catch for anything unexpected.
Specific vs General Exceptions
Catching specific exceptions is better than catching everything:
# Good - specific
except ValueError:
print("Invalid number format")
# Less good - too general
except:
print("Something went wrong")
Specific exceptions let you respond appropriately to different problems. The general catch should be a last resort.
Never Silently Swallow Errors
This is dangerous:
try:
result = convert(value)
except:
pass # Silently ignore errors
If something goes wrong, you'll never know. Always log or display errors, even if you handle them gracefully.
Protecting the Main Loop
Wrap your main loop's core logic to prevent any single error from crashing the entire program:
while True:
try:
choice = show_menu()
if choice == "5":
break
handle_choice(choice)
except KeyboardInterrupt:
print("\nExiting...")
break
except Exception as e:
print(f"An error occurred: {e}")
print("Please try again.")
The KeyboardInterrupt catch handles Ctrl+C gracefully. The general exception catch keeps the program running if something unexpected happens.
Testing Error Handling
Deliberately try to break your program:
- Enter extremely large numbers
- Paste random text
- Press Ctrl+C mid-operation
- Enter empty strings
Each test verifies your error handling works. Fix any crashes you discover.
The Professional Mindset
Amateur code works when everything goes right. Professional code works when things go wrong. Error handling is what separates "it works on my machine" from "it works reliably everywhere."
Your converter now handles the unexpected — a significant step toward professional-quality code.