Kramizo
Log inSign up free
HomeCIE IGCSE Computer ScienceProgramming concepts: exception handling (use of try/except or equivalent)
CIE · IGCSE · Computer Science · Revision Notes

Programming concepts: exception handling (use of try/except or equivalent)

1,965 words · Last updated May 2026

Ready to practise? Test yourself on Programming concepts: exception handling (use of try/except or equivalent) with instantly-marked questions.
Practice now →

What you'll learn

Exception handling is a programming technique used to manage runtime errors that occur during program execution. This topic focuses on the try/except structure (Python) or equivalent constructs in other languages, enabling programs to respond gracefully to unexpected conditions rather than crashing. You will learn how to implement robust code that anticipates potential errors and handles them appropriately.

Key terms and definitions

Exception — An error that occurs during program execution (runtime) which disrupts the normal flow of instructions, such as dividing by zero or attempting to open a non-existent file.

Runtime error — An error that occurs while a program is executing, after it has been successfully compiled or interpreted, often caused by invalid user input or unexpected conditions.

try block — A section of code that is monitored for exceptions; any code that might generate an error is placed within this block.

except block — A section of code that executes when a specific exception occurs in the corresponding try block, allowing the program to handle the error gracefully.

Error handling — The process of anticipating, detecting and resolving programming errors or exceptions to prevent program crashes.

Validation — The process of checking user input or data to ensure it meets specific criteria before processing, often used alongside exception handling.

Syntax error — An error in the code structure that prevents the program from running, detected before execution (not handled by try/except).

Logic error — An error in the program's algorithm that produces incorrect results but doesn't crash the program (not directly handled by try/except).

Core concepts

Understanding runtime errors

Runtime errors occur during program execution when the code encounters an unexpected condition. Unlike syntax errors, which prevent code from running at all, runtime errors allow the program to start but cause it to crash when the problematic line is reached.

Common runtime errors in IGCSE programming include:

  • Type errors: Attempting operations on incompatible data types (e.g., adding a string to an integer)
  • Division by zero: Performing division or modulus operations where the divisor is zero
  • Index errors: Accessing array or list elements using invalid indices
  • File errors: Attempting to open, read or write files that don't exist or lack permissions
  • Value errors: Passing arguments of the correct type but inappropriate value to a function

Without exception handling, these errors terminate program execution immediately and display error messages that may confuse end users.

The try/except structure

The try/except structure provides a mechanism to catch and handle exceptions. The basic syntax in Python (the primary language for CIE IGCSE) is:

try:
    # Code that might cause an error
    risky_operation()
except:
    # Code that runs if an error occurs
    handle_error()

When Python encounters a try block, it attempts to execute the code within it. If an exception occurs, execution immediately jumps to the corresponding except block, which contains code to handle the error. If no exception occurs, the except block is skipped entirely.

The program continues running after the try/except structure completes, preventing crashes and maintaining user experience.

Specific exception handling

Rather than catching all exceptions with a general except clause, programmers can target specific error types. This approach provides more precise control over error handling:

try:
    number = int(input("Enter a number: "))
    result = 100 / number
except ValueError:
    print("That's not a valid number")
except ZeroDivisionError:
    print("Cannot divide by zero")

Common exception types in CIE IGCSE Python programming include:

  • ValueError: Invalid value for an operation (e.g., converting "abc" to integer)
  • ZeroDivisionError: Division or modulus by zero
  • IndexError: List or array index out of range
  • FileNotFoundError: Attempting to access a non-existent file
  • TypeError: Operation on incompatible data types

Using specific exception types makes debugging easier and provides more helpful feedback to users.

The else clause

The else clause can be added to try/except structures to execute code only when no exception occurs:

try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Invalid age entered")
else:
    print(f"You are {age} years old")
    # Additional processing for valid input

The else block runs only if the try block completes without raising an exception. This separates error-free execution paths from exception handling, improving code readability.

The finally clause

The finally clause executes regardless of whether an exception occurred, making it useful for cleanup operations:

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    file.close()  # Ensures file is closed even if error occurs

Common uses for finally include:

  • Closing files
  • Releasing network connections
  • Saving data before exit
  • Displaying completion messages

At IGCSE level, finally is less commonly required but demonstrates understanding of comprehensive exception handling.

Exception handling with validation

Validation and exception handling work together to create robust programs. Validation checks data before processing, while exception handling manages unexpected errors that bypass validation:

def get_positive_integer():
    while True:
        try:
            number = int(input("Enter a positive integer: "))
            if number > 0:
                return number
            else:
                print("Number must be positive")
        except ValueError:
            print("Please enter a valid integer")

This approach combines:

  1. Exception handling (try/except) to catch type conversion errors
  2. Validation (if statement) to check the value meets requirements
  3. Loops (while True) to repeatedly request input until valid data is received

This pattern is essential for IGCSE programming tasks requiring user input.

Practical applications

Exception handling is crucial in scenarios where external factors can cause errors:

File operations: Files may not exist, lack read/write permissions, or be in use by other programs.

try:
    with open("studentdata.txt", "r") as file:
        data = file.readlines()
except FileNotFoundError:
    print("Student data file not found")
    data = []  # Use empty list as default

User input processing: Users frequently enter unexpected data that causes type conversion failures.

try:
    score = int(input("Enter test score: "))
    percentage = (score / 100) * 100
except ValueError:
    print("Score must be a number")
    percentage = 0

Mathematical operations: Division operations should check for zero divisors.

try:
    average = total / count
except ZeroDivisionError:
    print("Cannot calculate average with no items")
    average = 0

Worked examples

Example 1: Basic exception handling for calculator program

Question: Write a program that asks the user for two numbers and divides the first by the second. Use exception handling to manage potential errors. The program should continue running even if errors occur. [6 marks]

Mark scheme solution:

try:
    num1 = float(input("Enter first number: "))  # [1 mark]
    num2 = float(input("Enter second number: "))  # [1 mark]
    result = num1 / num2  # [1 mark]
    print(f"Result: {result}")
except ValueError:  # [1 mark]
    print("Please enter valid numbers")
except ZeroDivisionError:  # [1 mark]
    print("Cannot divide by zero")  # [1 mark]

Marking points:

  • Correct use of try block (1 mark)
  • Two input statements with appropriate conversion (1 mark each)
  • Correct use of except ValueError to catch invalid input (1 mark)
  • Correct use of except ZeroDivisionError to catch division by zero (1 mark)
  • Appropriate error messages (1 mark)

Example 2: File handling with exceptions

Question: A program needs to read student names from a text file called "students.txt" with one name per line. Write code that handles the situation where the file doesn't exist, displaying an appropriate message and using an empty list instead. [5 marks]

Mark scheme solution:

try:  # [1 mark]
    file = open("students.txt", "r")  # [1 mark]
    students = file.readlines()
    file.close()
except FileNotFoundError:  # [1 mark]
    print("Students file not found")  # [1 mark]
    students = []  # [1 mark - default value]

Marking points:

  • Correct try block structure (1 mark)
  • File opening with correct mode (1 mark)
  • Specific FileNotFoundError exception (1 mark)
  • Appropriate error message (1 mark)
  • Providing default value when file not found (1 mark)

Example 3: Validated input with exception handling

Question: Write a function called get_age() that repeatedly asks the user to enter their age until a valid integer between 5 and 18 (inclusive) is entered. Use exception handling for invalid input. The function should return the valid age. [7 marks]

Mark scheme solution:

def get_age():  # [1 mark]
    while True:  # [1 mark]
        try:  # [1 mark]
            age = int(input("Enter age (5-18): "))  # [1 mark]
            if 5 <= age <= 18:  # [1 mark]
                return age  # [1 mark]
            else:
                print("Age must be between 5 and 18")
        except ValueError:  # [1 mark]
            print("Please enter a valid integer")

Marking points:

  • Function definition with correct name (1 mark)
  • Loop structure to repeat until valid input (1 mark)
  • Correct try block (1 mark)
  • Input statement with integer conversion (1 mark)
  • Range validation using appropriate comparison (1 mark)
  • Return statement for valid input (1 mark)
  • Exception handling for ValueError (1 mark)

Common mistakes and how to avoid them

  • Using bare except clauses: Writing except: without specifying the error type catches all exceptions, including system errors. This can hide bugs and make debugging difficult. Always use specific exception types like except ValueError: or except ZeroDivisionError: where possible.

  • Placing too much code in try blocks: Students often wrap entire programs in a single try block. This makes it difficult to identify where errors occur. Only place code that might cause the specific exception you're handling inside the try block.

  • Forgetting to provide user feedback: Exception blocks that catch errors but provide no output leave users confused about what went wrong. Always include print() statements or other feedback mechanisms in except blocks to inform users of errors.

  • Confusing exception handling with validation: Exception handling manages unexpected runtime errors, while validation checks whether data meets requirements. Both are needed in robust programs. Use if statements for validation (checking ranges, formats) and try/except for handling type conversions and external resource errors.

  • Not continuing program execution: After handling an exception, students sometimes forget to allow the program to continue or retry. Use loops combined with exception handling to repeatedly request valid input rather than accepting the first error and moving on.

  • Using exception handling for logic errors: Try/except blocks cannot fix logic errors (algorithmic mistakes). If your program produces incorrect results without crashing, review your algorithm rather than adding exception handling.

Exam technique for exception handling

  • Identify command words carefully: "Implement error handling" or "use exception handling" directly requires try/except structures. "Write robust code" or "handle invalid input" may require validation, exception handling, or both. Consider what errors could realistically occur in the scenario described.

  • Structure answers clearly: In written code responses, use proper indentation to show the relationship between try, except, else and finally blocks. Examiners award marks for correct structure as well as functionality. Comment your code if marks are available for explanations.

  • Match exception types to scenarios: When the question describes specific error conditions (file not found, invalid number input, division by zero), use the corresponding specific exception type. General except clauses receive fewer marks unless the question specifically requires catching multiple error types.

  • Consider mark allocation: Questions worth 2-3 marks typically require basic try/except structure. Questions worth 5-7 marks usually require specific exception types, multiple except clauses, or combination with validation and loops. Allocate your code complexity to match available marks.

Quick revision summary

Exception handling uses try/except blocks to manage runtime errors gracefully without program crashes. Place potentially problematic code in the try block and error-handling code in corresponding except blocks. Use specific exception types (ValueError, ZeroDivisionError, FileNotFoundError, IndexError) for precise error management. Combine exception handling with validation and loops for robust user input processing. The else clause runs when no exception occurs; finally executes regardless. Exception handling is essential for file operations, user input processing and mathematical operations where external factors may cause errors.

Free for IGCSE students

Lock in Programming concepts: exception handling (use of try/except or equivalent) with real exam questions.

Free instantly-marked CIE IGCSE Computer Science practice — 45 questions a day, no card required.

Try a question →See practice bank