Skip to content

Defensive Programming: Error Handling and LoggingActivities & Teaching Strategies

Active learning works well here because students need hands-on experience to understand how errors affect programs and how logging reveals hidden issues. By writing and testing their own error handlers, they see resilience in action rather than just hearing about it.

Secondary 4Computing4 activities25 min45 min

Learning Objectives

  1. 1Explain the role of exception handling in preventing unexpected program termination and revealing security vulnerabilities.
  2. 2Analyze log files to identify patterns indicative of attempted security breaches or system malfunctions.
  3. 3Construct a Python program that implements robust error handling using try-except blocks and custom exceptions.
  4. 4Design a logging strategy that includes appropriate severity levels and secure storage for audit purposes.
  5. 5Evaluate the trade-offs between detailed logging for security and potential performance impacts or information leakage.

Want a complete lesson plan with these objectives? Generate a Mission

30 min·Pairs

Pair Programming: Error Handler Challenge

Pairs receive a vulnerable function processing user inputs. They add input validation and try-except blocks to handle exceptions gracefully. Test with edge cases like empty strings or invalid numbers, then swap code for peer review.

Prepare & details

Explain the importance of proper error handling in preventing system vulnerabilities.

Facilitation Tip: During Pair Programming: Error Handler Challenge, circulate and ask pairs to explain their error handling choices before they run the code, forcing them to justify their defensive strategies.

Setup: Groups at tables with access to research materials

Materials: Problem scenario document, KWL chart or inquiry framework, Resource library, Solution presentation template

AnalyzeEvaluateCreateDecision-MakingSelf-ManagementRelationship Skills
45 min·Small Groups

Small Groups: Logging Scenarios

Groups implement logging in a simulated banking app for transactions. Use logging levels (DEBUG, INFO, ERROR) to record events. Introduce faults like failed logins, review logs to trace issues, and discuss audit usefulness.

Prepare & details

Analyze how logging can assist in detecting and responding to security incidents.

Facilitation Tip: For Logging Scenarios, provide a template with placeholder severity levels and timestamps so students focus on selecting the right level instead of formatting details.

Setup: Groups at tables with access to research materials

Materials: Problem scenario document, KWL chart or inquiry framework, Resource library, Solution presentation template

AnalyzeEvaluateCreateDecision-MakingSelf-ManagementRelationship Skills
35 min·Whole Class

Whole Class: Attack Simulation Demo

Display a live demo of an app with poor handling under attack inputs. Class predicts failures, then implements fixes collectively via shared code editor. Analyze generated logs to reconstruct the attack sequence.

Prepare & details

Construct a strategy for implementing secure error handling and logging in a software application.

Facilitation Tip: In the Attack Simulation Demo, replay the same attack twice: once with poor error handling and once with robust logging, so students directly compare the outcomes.

Setup: Groups at tables with access to research materials

Materials: Problem scenario document, KWL chart or inquiry framework, Resource library, Solution presentation template

AnalyzeEvaluateCreateDecision-MakingSelf-ManagementRelationship Skills
25 min·Individual

Individual: Log Analysis Hunt

Provide buggy code output with logs from test runs. Students identify error sources, propose handlers, and rewrite sections. Share findings in a class gallery walk for feedback.

Prepare & details

Explain the importance of proper error handling in preventing system vulnerabilities.

Facilitation Tip: During Log Analysis Hunt, assign each student a different log file snippet to analyze, then have them present their findings to the class for peer learning.

Setup: Groups at tables with access to research materials

Materials: Problem scenario document, KWL chart or inquiry framework, Resource library, Solution presentation template

AnalyzeEvaluateCreateDecision-MakingSelf-ManagementRelationship Skills

Teaching This Topic

Teachers should model debugging live, showing how unhandled exceptions disrupt programs while handled ones allow graceful exits. Avoid teaching logging as a standalone task; instead, tie it to real incidents like failed logins or corrupted files. Research shows students grasp defensive programming better when they experience the consequences of weak defenses firsthand in controlled environments.

What to Expect

Students will confidently implement try-except blocks to handle common exceptions, validate inputs for security, and use the logging module to record events at appropriate severity levels. They will explain why these practices matter for security and performance in real-world applications.

These activities are a starting point. A full mission is the experience.

  • Complete facilitation script with teacher dialogue
  • Printable student materials, ready for class
  • Differentiation strategies for every learner
Generate a Mission

Watch Out for These Misconceptions

Common MisconceptionDuring Pair Programming: Error Handler Challenge, watch for students who think crashing the program is the only way to know something went wrong.

What to Teach Instead

Ask pairs to compare their handled programs with unhandled versions, then discuss how graceful exits prevent attackers from gaining system access or seeing error details.

Common MisconceptionDuring Logging Scenarios, watch for students who believe print statements are as effective as logging modules for security purposes.

What to Teach Instead

Have students review logs generated by print statements versus the logging module, highlighting missing timestamps, severity levels, and security risks in exposed data.

Common MisconceptionDuring whole-class discussions about logging verbosity, watch for students who assume more logs are always better.

What to Teach Instead

Guide students to examine log configs in the Logging Scenarios activity, then revise them to balance detail with security and storage constraints.

Assessment Ideas

Quick Check

After Pair Programming: Error Handler Challenge, collect students' try-except snippets and assess them for correct exception types, user-friendly messages, and resilience against common errors.

Exit Ticket

During Logging Scenarios, ask students to submit their log configs for a simulated SQL injection attempt, then evaluate whether they included timestamps, severity levels, and masked sensitive data.

Discussion Prompt

After the Attack Simulation Demo, facilitate a class discussion where students justify their log choices for a user registration system, assessing their understanding of critical events, severity levels, and performance trade-offs.

Extensions & Scaffolding

  • Challenge early finishers to design a custom exception class for a new error type, write code that triggers it, and implement appropriate logging for investigation.
  • For students who struggle, provide pre-written try-except templates with gaps for them to fill in the correct exception types and messages.
  • Deeper exploration: Have students research how cybersecurity teams use logs to detect advanced persistent threats, then present their findings to the class.

Key Vocabulary

Exception HandlingA programming mechanism to manage runtime errors, preventing program crashes and allowing for graceful recovery or reporting.
Try-Except BlockA Python construct used to test a block of code for errors and handle any exceptions that occur within it.
LoggingThe process of recording events, errors, and other significant information during program execution, often used for debugging and security analysis.
Severity LevelsCategories within logging (e.g., DEBUG, INFO, WARNING, ERROR, CRITICAL) that indicate the importance or impact of a logged event.
Audit TrailA chronological record of system activities and user actions, essential for security reviews and forensic investigations.

Ready to teach Defensive Programming: Error Handling and Logging?

Generate a full mission with everything you need

Generate a Mission