Programming technique · B2.1.3, B2.1.4
Debugging and exceptions
Exception handling lets a program respond safely to failures it can meaningfully handle. Debugging uses evidence to locate and correct faults, including logic errors that do not produce an exception.
Three common error categories
| Error type | What happens | Example |
|---|---|---|
| Syntax error | The program cannot compile because the language rules were broken. | Missing semicolon or misspelled keyword. |
| Runtime error | The program starts but fails during execution. | Invalid number conversion or unavailable file. |
| Logic error | The program runs but produces the wrong result. | Incorrect formula or branch order. |
| Error type | What happens | Example |
|---|---|---|
| Syntax error | The interpreter cannot begin normal execution because the language rules were broken. | Missing colon, incorrect indentation or misspelled keyword. |
| Runtime error | The program starts but fails during execution. | Invalid number conversion or unavailable file. |
| Logic error | The program runs but produces the wrong result. | Incorrect formula or branch order. |
Potential failure points need different responses
Unexpected input
A conversion can fail when the user enters text where a number is required. A specific handler can explain what input is accepted.
Resource unavailable
A required file or other resource may not be accessible. Handle the failure at the point where the program can respond usefully.
Logic error
The program may execute normally but calculate the wrong answer. This is a debugging problem; wrapping the code in a broad exception handler does not fix the logic.
Catch a specific exception
Handle a specific exception
Catch the most specific exception you can handle meaningfully. A catch block should explain what the user can do next rather than merely printing a technical stack trace.
Handle the most specific exception you can respond to meaningfully. An except block should explain what the user can do next rather than merely printing a technical traceback.
Finally
A finally block runs whether or not an exception occurred. It is useful for cleanup or guaranteed final actions. Later file-processing examples normally use language features that close resources automatically, but finally remains part of the exception-handling model required here.
Debug a logic error with evidence
The code below should apply a 25% discount to 80, so the expected final price is 60. Instead it prints 100.
| Evidence step | subtotal | discount | finalPrice | Conclusion |
|---|---|---|---|---|
| Before discount calculation | 80 | — | — | Input state is correct. |
| After discount calculation | 80 | 20 | — | The discount itself is correct. |
| After final calculation | 80 | 20 | 100 | The final operation adds instead of subtracting. |
A trace table exposes the bad state transition. A breakpoint before the final calculation and one step of execution would show the same evidence in a debugger. A temporary print statement can also expose the intermediate values. These techniques are alternatives for gathering evidence, not different kinds of errors.
Change one suspected cause at a time so the result of each test remains meaningful.
- Reproduce the problem with a specific test case.
- State the expected and actual result.
- Narrow the fault using a trace table, print statement, breakpoint or step execution.
- Change one suspected cause.
- Retest the original case and nearby boundary cases.
Check your understanding
Answer each question before opening the model answer.
-
A user types "twelve" where int conversion is attempted. What kind of failure is this and what response is appropriate?
Reveal model answer
It is an unexpected-input runtime failure. Catch the specific conversion exception and give a useful input message.
-
A program prints 100 when the expected price is 60, but no exception occurs. Should you add a catch block?
Reveal model answer
No. That is a logic error. Trace intermediate values, use a breakpoint/step execution or temporary prints to locate the wrong operation.
-
Why is catching every Exception with one vague message usually weak?
Reveal model answer
Different failures have different causes and useful responses. A broad handler can hide evidence and make unrelated bugs harder to diagnose.
-
What is the purpose of finally?
Reveal model answer
It runs a guaranteed final block whether the protected operation succeeds or an exception is handled.
Validation is not the same as exception handling
Range, presence, length and format checks prevent invalid values; exceptions handle failures that still occur.
Do not hide logic errors
A broad exception handler cannot make an incorrect calculation correct.
Keep evidence
Record the test input, variable values and exact correction so the fault can be explained and reproduced.
Challenges Choose one
Choose a challenge that feels appropriate for you. Code heat is only a rough estimate, not a fixed level.
Safe Integer Input
SelectedAsk the user for a whole number. Prevent the program from crashing when text or a decimal is entered. Keep asking until a valid integer is provided, then display the accepted value.
Reliable Division
SelectedAsk for two integers and divide the first by the second. Handle invalid numeric input and division by zero with specific messages. The program must not catch every possible exception as one vague error.
Broken Program Investigation
SelectedCollect the debugging evidence sheet from the front of the class. Create or obtain a short program containing at least one syntax error, one runtime error and one logic error. Use compiler messages, print tracing or breakpoints, and step-by-step execution to locate and correct each fault. Record the test case, evidence, cause and correction for every error, then hand the sheet to your teacher.
Expression Parser
SelectedAllow the user to enter a calculation as one string, such as 16+8, 120/5 or 9*13. Identify the operator, extract both operands and output the result. Support +, -, * and /. Detect malformed expressions, non-numeric operands and division by zero without crashing.
Selected challenge
This choice is shared with the portfolio setup page.
Plan your solution in handwritten pseudocode
Before opening your IDE or writing any program code, handwrite pseudocode for this challenge on paper.
Not marked complete. If you submit now, the GitHub README will record “No”.
Create your challenge folder
Run this command after planning. It creates the correct empty folder inside your portfolio.
Complete the challenge
Use your handwritten pseudocode as the starting plan, then write and test your solution in the folder created above.
Optional two-level scaffold
Try from your handwritten pseudocode first. Scaffold gives some structure; Scaffold + comments gives stronger guidance. Use only the level you need, and update your pseudocode first if the support changes your plan.
Submit for review
Run this when your program is complete. It creates the README, commits the folder and pushes it. The README records whether you marked the handwritten pseudocode as complete; the paper itself is handed to your teacher separately.