Welcome to Simple Error Handling Techniques!
Have you ever played a video game that suddenly froze, or typed your name into a website form only to see a red warning box pop up? In programming, things don't always go according to plan. Users type unexpected answers, calculations go wrong, or a simple typo can bring everything to a halt.
In this chapter of Unit 4: Digital Development Concepts, you will learn how to identify different types of programming errors, how to validate user input before it causes trouble, and how to write programs that deal gracefully with mistakes instead of crashing. Don't worry if programming seems daunting at first—once you know what clues to look for, catching and handling errors is just like solving a puzzle!
1. The Three Core Types of Programming Errors
When writing code, mistakes happen to everyone from beginners to professional software engineers. In CCEA GCSE Digital Technology, errors are classified into three distinct categories:
A. Syntax Errors
What is it? A syntax error is a break in the grammatical rules of the programming language. Just like human languages have rules for spelling and punctuation, programming languages have strict syntax rules that must be followed perfectly.
What causes it?
• Spelling mistakes in reserved programming keywords (for example, typing prnt instead of print).
• Missing punctuation, such as unclosed quotation marks (""), missing brackets (()), or missing colons (:).
• Invalid indentation or layout errors.
How is it detected? The compiler or interpreter flags a syntax error before or during translation. Because the computer cannot understand the instruction, the program will refuse to run at all.
Everyday Analogy: Imagine reading a sentence that says: "The dog ran the through fence blue." The words are there, but the grammar is so broken that your brain pauses to figure out what it means.
B. Execution / Run-Time Errors
What is it? An execution error (also called a run-time error) occurs while the program is actively running. The syntax is completely fine, so the program starts running, but it suddenly encounters an instruction that is impossible to carry out, causing it to crash or terminate abnormally.
What causes it?
• Division by zero: Asking the computer to calculate \(10 / 0\) (which is mathematically undefined).
• Data type conversion failures: Trying to convert the word "hello" into a whole number (integer).
• Index out of range: Trying to access the 10th item in a list that only contains 3 items.
• Missing files: Instructing the program to open a file path that does not exist on the hard drive.
Everyday Analogy: Imagine following a recipe that says: "Crack two eggs into the bowl, then bake on the surface of the sun for 10 minutes." The sentence is grammatically correct, but physically impossible to perform, so the whole cooking process halts!
C. Logic Errors
What is it? A logic error is a flaw in the design or thinking behind the program. The program has correct syntax and runs from start to finish without crashing, but it produces the wrong or unexpected output.
What causes it?
• Using the wrong mathematical operator (e.g., writing \(total = price + discount\) instead of \(total = price - discount\)).
• Incorrect Boolean comparison symbols (e.g., writing \(age > 18\) instead of \(age \ge 18\)).
• Incorrect loop conditions that repeat one time too many or too few (off-by-one errors).
Everyday Analogy: You enter directions into a satellite navigation system to go to Belfast, but you accidentally type in Dublin. The car drives smoothly the entire way with no mechanical breakdowns, but you end up in the wrong city!
Key Takeaway for Error Types:
• Syntax Error: Broken grammar → Will not translate or start.
• Execution / Run-Time Error: Illegal action → Crashes mid-run.
• Logic Error: Flawed thinking → Runs fully, but gives the wrong answer.
2. Defensive Error Prevention: Input Validation
One of the best ways to stop execution errors from happening is to prevent bad data from entering your program in the first place. This is called input validation—an automatic check carried out by the computer to ensure user input is sensible, reasonable, and follows specific rules before processing.
Here are the six essential validation checks you need to know for your exam:
1. Range Check:
Ensures numerical data falls within specified minimum and maximum limits.
Example: Checking that a birth month falls in the range \(1 \le \text{month} \le 12\).
2. Length Check:
Ensures that entered text (a string) has an acceptable number of characters (not too short and not too long).
Example: Checking that a new password contains at least \(8\) characters.
3. Type Check (Data Type Check):
Confirms that the entered value matches the expected data type.
Example: Ensuring an age field receives an integer (e.g., \(16\)) rather than letters (e.g., "sixteen").
4. Presence Check:
Ensures that a mandatory field cannot be left blank or empty.
Example: Requiring an applicant to fill in their surname before submitting an online application.
5. Format Check / Pattern Matching:
Confirms that the input follows a strict predefined layout or pattern.
Example: Checking that a Northern Ireland postcode matches the pattern BT## #AA (letters and numbers in set positions) or checking an email address for an @ symbol.
6. Lookup Check / Set Membership:
Checks that an entered value exists within a predetermined list of allowed values.
Example: Ensuring that a day of the week input matches one item in the list ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], or selecting gender from ["M", "F"].
Memory Trick: Remember the phrase "Really Lovely People Take Fantastic Lunches" → Range, Length, Presence, Type, Format, Lookup!
3. Error Handling Mechanisms in Code
What happens when bad data is entered or an unforeseen issue arises? Good software uses built-in error handling mechanisms to keep running smoothly:
A. Validation Loops (Iterative Trapping)
A validation loop uses a conditional loop (such as a while loop) to trap invalid input. If the user enters invalid data, the program outputs a helpful message and asks them to try again until valid data is supplied.
How it works in practice:
1. Prompt the user for input.
2. Check if the input fails a validation rule (e.g., while \(age < 0\) or \(age > 120\)).
3. If invalid, display an error message and re-prompt the user.
4. Once valid, exit the loop and continue processing.
B. Structured Exception Handling (Try / Except / Catch)
When an unexpected run-time event occurs (such as dividing by zero or failing to open a file), it generates an exception. If unhandled, this exception crashes the program immediately.
Structured exception handling uses code blocks (such as try ... except or try ... catch) to safely intercept these exceptions. The program tries to execute a risky line of code; if an error occurs, control jumps to the except block to handle it smoothly instead of crashing.
C. User Feedback and Error Messages
A good program must communicate effectively with the user. Error messages should always be:
• Clear and non-technical: Avoid confusing system error codes like "Exception 0x80004005".
• Descriptive and constructive: Tell the user what went wrong and give clear instructions on how to fix it (e.g., "Invalid date. Please enter a month between 1 and 12.").
Key Takeaway: Defensive coding combines input validation (stopping errors at the door), validation loops (re-prompting until correct), and exception handling (catching crashes safely).
4. Testing Strategies & Test Data Classifications
To prove that your error handling and validation routines work properly, you must test your code using a structured test plan. In Unit 4 exam questions, you will often be asked to select test data from three standard categories:
Let's use an example of a field that accepts test scores from \(1\) to \(100\):
1. Valid / Normal Data:
Data that sits comfortably inside the allowed boundaries and should be accepted without issue.
Example for 1 to 100: \(50\), \(75\), or \(12\).
2. Extreme / Boundary Data:
Data at the very outer edges (the absolute minimum and maximum values) of the acceptable range. These values should be accepted.
Example for 1 to 100: Exactly \(1\) and \(100\).
3. Invalid / Erroneous Data:
Data that falls completely outside the acceptable limits or is of the wrong data type. This data must be rejected with an appropriate error message.
Example for 1 to 100: \(0\), \(105\), \(-5\), or text like "one hundred".
5. Examiner Tips & Common Pitfalls to Avoid
CCEA examiners frequently highlight common mistakes made by students in the written exam. Keep these points in mind to secure top marks (from grade \(G\) up to \(A^*\)):
Pitfall 1: Confusing Validation with Verification
• Validation: An automatic check by the computer to make sure data is reasonable, sensible, and valid (e.g., range check, presence check).
• Verification: Checking that data has been copied across accurately from the original source (e.g., double data entry where you enter a password twice, or proofreading text against a paper form).
Pitfall 2: Using Vague Terminology
Never use informal words like "the code glitched", "it froze", or "the system broke". Use precise specification terms: syntax error, logic error, run-time / execution error, presence check, or range check.
Pitfall 3: Giving Generic Answers to Scenarios
If an exam question asks about an online cinema booking system, don't just say "an error message appears". Relate it directly to the context: "an error message appears informing the customer that the number of tickets requested exceeds the maximum limit of 10."
Pitfall 4: Incomplete Exception Explanations
If asked what causes a run-time error in a calculation, do not simply say "doing maths" or "dividing". Clearly specify the exact trigger: "attempting to divide a number by zero".
Quick Chapter Summary Checklist
Make sure you can confidently do the following before your Unit 4 exam:
• Define and tell the difference between syntax, execution / run-time, and logic errors.
• Identify the \(6\) main validation checks: Range, Length, Type, Presence, Format, and Lookup.
• Explain how validation loops and try / except blocks handle errors safely.
• Provide examples of Normal, Boundary / Extreme, and Invalid / Erroneous test data for any given scenario.
• Clearly explain the difference between validation and verification.