6.7 - Writing Programs that Handle Errors
What is robust programming?
Robust programming involves designing programs that can handle errors and unexpected situations effectively, without crashing or behaving incorrectly. This approach ensures that a program remains reliable even when users provide input that differs from what was anticipated. For instance, if a program expects a number but receives text, a robust design will manage this gracefully rather than failing.
Input validation
Input validation is a technique where a program checks whether user-provided data meets specific requirements before processing it. This prevents errors that could occur if the data is incorrect or unsuitable, such as when a program expects an integer (a whole number) but receives a string (text). By validating input, the program can prompt the user to correct their entry or reject invalid data, maintaining stability.
Common input validation checks
- Range check - Ensures the data falls within an acceptable range, for example, verifying that an entered age is between 0 and 120 to avoid unrealistic values.
- Presence check - Confirms that data has been entered and not left blank, such as requiring a name field to be filled in.
- Format check - Verifies that the data follows the expected structure, like ensuring a date is in the format dd/mm/yyyy (day/month/year).
Authentication
Authentication is the process of verifying a user's identity to control access to sensitive data or program features.
Password-based authentication
Passwords are a common authentication tool. The program stores the correct password securely and asks the user to enter it. If the input matches, access is granted; otherwise, it is denied.
Here is an example in pseudocode (a simplified way of writing code logic without specific language syntax):
In this setup, the comparison determines whether the user can continue, preventing unauthorised entry.
Improving password security
To enhance the security of password systems, programs can implement additional measures that make it harder for unauthorised users to gain access.
Methods to strengthen password authentication:
- Enforce strong passwords
- Limit incorrect attempts
- Request random characters
Preventing security issues through robustness
Robust programming plays a key role in security by stopping unexpected inputs from causing harm. For example, without proper input validation, a hacker might enter malicious data to exploit weaknesses, forcing the program to perform unintended actions.