Skip to content
Computer Science · 11th Grade · Object-Oriented Programming · Weeks 19-27

Error Handling and Exceptions

Implementing robust code that gracefully handles unexpected situations and errors.

Common Core State StandardsCSTA: 3B-AP-16

About This Topic

Every program encounters unexpected conditions: invalid user input, missing files, failed network connections, division by zero. Error handling is the discipline of anticipating these conditions and writing code that responds gracefully rather than crashing. For US 11th graders aligned to CSTA 3B-AP-16, this unit shifts the mindset from 'writing code that works in ideal conditions' to 'writing code that works reliably in real conditions.'

Java and Python both use exception-based error handling with try-catch (Java) or try-except (Python) blocks. The key conceptual move is understanding the three categories of errors: compile-time errors caught by the compiler before the program runs, runtime exceptions that occur during execution (null pointer, index out of bounds, type mismatch), and logical errors where the program runs without crashing but produces wrong results. Exception handling addresses runtime errors specifically--logical errors require debugging and testing.

Active learning is particularly effective here because the intuition for good exception handling builds through practice with real code failures. Debugging exercises where students encounter and fix unhandled exceptions, and design challenges where students determine which exceptions to catch and how to recover, develop practical skill faster than reading about exception syntax.

Key Questions

  1. Explain the importance of error handling in creating reliable software.
  2. Analyze different types of errors (compile-time, runtime, logical) and how to address them.
  3. Design a strategy for handling exceptions in a given program to prevent crashes.

Learning Objectives

  • Identify and classify common runtime errors in a given Java or Python program.
  • Analyze the potential consequences of unhandled exceptions on software reliability and user experience.
  • Design and implement appropriate try-catch or try-except blocks to handle specific exceptions in a program.
  • Evaluate the effectiveness of different exception handling strategies in preventing program crashes.
  • Create a program that demonstrates robust error handling for invalid user input and potential file access issues.

Before You Start

Basic Programming Constructs (Variables, Data Types, Control Flow)

Why: Students need a foundational understanding of how programs execute and store data to comprehend where errors can occur.

Introduction to Functions/Methods

Why: Understanding function calls and returns is necessary to grasp how exceptions can propagate up the call stack.

Input/Output Operations

Why: Many common runtime errors involve issues with reading from or writing to files or user input, making this a direct prerequisite.

Key Vocabulary

ExceptionAn event that occurs during program execution that disrupts the normal flow of instructions. Exceptions are used to signal and handle errors.
Try-Catch BlockA control structure in Java used to handle exceptions. Code that might cause an exception is placed in the 'try' block, and the 'catch' block specifies how to respond if an exception occurs.
Try-Except BlockA control structure in Python used to handle exceptions. Code that might cause an exception is placed in the 'try' block, and the 'except' block specifies how to respond if an exception occurs.
Runtime ErrorAn error that occurs while the program is executing, often due to unexpected conditions like invalid input or resource unavailability. These are also known as exceptions.
Unhandled ExceptionAn exception that is not caught by a try-catch or try-except block. If an unhandled exception occurs, the program typically terminates abruptly.

Watch Out for These Misconceptions

Common MisconceptionCatching every exception with a generic catch block is good defensive programming.

What to Teach Instead

Catching all exceptions with a single broad catch (Exception e) or catch-all block hides errors instead of handling them. Code may silently fail in ways that are very hard to debug later. Best practice is to catch specific exception types and handle each appropriately--using the broad catch only as a last resort with logging.

Common MisconceptionIf a program compiles without errors, it will run without errors.

What to Teach Instead

Compile-time errors and runtime exceptions are completely different categories. A program can compile successfully and then throw exceptions during execution when it encounters conditions the compiler couldn't predict--like invalid user input, missing files, or unexpected null values.

Common MisconceptionException handling is only needed for file and network operations.

What to Teach Instead

Exceptions can arise from any operation: invalid array indices, null pointer dereferences, arithmetic errors, type conversion failures, and more. Robust software applies error handling wherever external input or uncertain conditions exist--not just at I/O boundaries.

Active Learning Ideas

See all activities

Real-World Connections

  • Software developers at companies like Google or Microsoft use exception handling extensively to ensure their applications, such as web browsers or operating systems, remain stable even when users perform unexpected actions or external services fail.
  • Financial institutions, like banks or trading platforms, rely on precise error handling to prevent data corruption or system crashes during critical transactions, ensuring the integrity of financial records and user accounts.
  • Game developers implement robust error handling to manage issues like corrupted save files or network disconnections, providing a smoother and more resilient gaming experience for players.

Assessment Ideas

Quick Check

Present students with short code snippets in Java or Python that contain common runtime errors (e.g., division by zero, index out of bounds). Ask them to identify the error, predict the output if unhandled, and then write the correct try-catch or try-except block to handle it.

Discussion Prompt

Pose the scenario: 'Imagine you are building a simple text editor. What are three potential runtime errors a user might encounter (e.g., trying to save to a read-only location, opening a corrupted file)? How would you use exception handling to inform the user and prevent a crash?'

Exit Ticket

Provide students with a program that simulates reading user input for an age. Ask them to write one try-except block in Python (or try-catch in Java) that specifically handles `ValueError` if the user enters non-numeric input, prompting them to re-enter a valid age.

Frequently Asked Questions

What is the difference between a checked and unchecked exception in Java?
Checked exceptions are conditions the compiler requires you to handle--like IOException or FileNotFoundException. If a method can throw a checked exception, the calling code must either catch it or declare it with throws. Unchecked exceptions (RuntimeExceptions) are not enforced by the compiler and represent programming errors like null dereferences or array index violations.
What does the finally block do in a try-catch?
A finally block runs after the try and catch blocks complete, regardless of whether an exception was thrown. It is used for cleanup code that must always execute--like closing a file, releasing a database connection, or freeing a resource. The finally block runs even if the try block returns or an exception is not caught.
When should you throw your own exceptions?
You should throw exceptions when a method encounters a condition that prevents it from fulfilling its contract and the calling code needs to be notified. For example, a withdraw() method might throw an InsufficientFundsException if the requested amount exceeds the balance. Custom exceptions make error conditions explicit and easier to handle specifically.
How does active learning help students write better error handling?
Exception handling intuition builds through encountering real failures. Debug exercises that present crashing code force students to diagnose the specific exception type, trace where it originated, and design targeted fixes. Code exchange activities--where groups try to crash each other's implementations--reveal gaps that self-review misses.