Revise Computingrevisecomputing.co.uk
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates

Knowledge organisers / Defensive Design

Anticipate misuse

All topicsPractise exam questions
Knowledge organiser

Defensive Design

301.16a

Predict invalid input.

What you need to know

Defensive design means writing code that handles unexpected or invalid input gracefully instead of crashing (e.g. wrapping int(input(...)) in try/except). Always assume the user will make mistakes.

Key points

  • Users may enter text when numbers are expected
  • Users may leave fields blank
  • Users may enter values outside the valid range
  • Plan for every possible wrong input

Code examples

Anticipating misuse
python
# Without defence — crashes on bad input
age = int(input("Age: "))  # Crashes if user types "abc"

# With defence
try:
    age = int(input("Age: "))
except ValueError:
    print("Please enter a number")