Code Companion
Java

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.

IB DP CS standards B2.1.3 and B2.1.4: Describe common exception-handling techniques and construct/use debugging techniques such as trace tables, breakpoint debugging, print statements and step-by-step execution.

Three common error categories

Error typeWhat happensExample
Syntax errorThe program cannot compile because the language rules were broken.Missing semicolon or misspelled keyword.
Runtime errorThe program starts but fails during execution.Invalid number conversion or unavailable file.
Logic errorThe program runs but produces the wrong result.Incorrect formula or branch order.
Error typeWhat happensExample
Syntax errorThe interpreter cannot begin normal execution because the language rules were broken.Missing colon, incorrect indentation or misspelled keyword.
Runtime errorThe program starts but fails during execution.Invalid number conversion or unavailable file.
Logic errorThe 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 stepsubtotaldiscountfinalPriceConclusion
Before discount calculation80Input state is correct.
After discount calculation8020The discount itself is correct.
After final calculation8020100The 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.

Debugging is a repeatable evidence cycle
flowchart TD A[Reproduce the problem] --> B[Compare expected and actual results] B --> C[Collect evidence with a trace, print or breakpoint] C --> D[Change one suspected cause] D --> E[Retest the original and boundary cases] E --> F{Is the problem fixed?} F -- No --> B F -- Yes --> G[Record the cause and correction]

Change one suspected cause at a time so the result of each test remains meaningful.

  1. Reproduce the problem with a specific test case.
  2. State the expected and actual result.
  3. Narrow the fault using a trace table, print statement, breakpoint or step execution.
  4. Change one suspected cause.
  5. Retest the original case and nearby boundary cases.

Check your understanding

Answer each question before opening the model answer.

  1. 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.

  2. 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.

  3. 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.

  4. 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

Challenge ID: PC-T05-C01 · Standards: B2.1.3

Ask 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

Challenge ID: PC-T05-C02 · Standards: B2.1.3, B2.3.2

Ask 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

Challenge ID: PC-T05-C03 · Standards: B2.1.4

Collect 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.

Code being investigated with a bug, magnifying glass, breakpoint and corrected result.

Expression Parser

Challenge ID: PC-T05-C04 · Standards: B2.1.2, B2.1.3, B2.1.4, B2.3.2

Allow 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.

Scaffold available