2.10 Robust Code
2.10.1 Characteristics of robust code
What Makes Code Robust?
Robust code is designed to cope with unexpected situations without crashing.
Characteristics:
Characteristics:
- Handles unexpected inputs
- Handles unexpected termination
- Produces specific and meaningful error messages
Handling Unexpected Input
Robust programs check input before using it.
Python example:
Python example:
try:
age = int(input("Enter your age: "))
print("Age entered:", age)
except ValueError:
print("Error: Please enter a whole number")
Handling Unexpected Termination
Programs can fail due to missing files or unavailable resources.
Python example:
Python example:
try:
file = open("data.txt", "r")
print(file.read())
file.close()
except FileNotFoundError:
print("Error: File not found")
2.10.2 Debugging: process and purpose
The Debugging Process
Debugging is the process of:
- Locating errors in code
- Correcting errors in code
2.10.3 Role of debugging in robust solutions
Why Debugging Matters
Debugging improves robustness by:
- Identifying weaknesses in logic
- Ensuring unexpected cases are handled
- Preventing crashes and data loss
2.10.4 Locating errors in code
Locating Errors
Errors may be identified through error messages or incorrect output.
Python example:
Python example:
numbers = [10, 20, 30]
print(numbers[3])
Error: Index out of range.
2.10.5 Correcting errors in code
Correcting Errors
Once identified, code must be corrected and tested.
Corrected Python example:
Corrected Python example:
numbers = [10, 20, 30]
print(numbers[2])
The index has been changed to a valid value.