IB COMPUTER SCIENCE | B2.1.3 Exception Handling

Lesson objective

Describe how programs use Python try/except, Java try/catch and finally to respond to failures, manage resources and distinguish handling from debugging.

Learn

B2.1.3 | EXCEPTION HANDLING

01 | A PROGRAM MEETS THE UNEXPECTED

A student types three where a program expects a number. A file has been moved. A calculation tries to divide by zero. Even a program that worked in your last test can encounter conditions it cannot handle by following its normal steps.

An exception is a runtime event represented by an exception object that interrupts normal execution. Exception handling provides a controlled route for responding to specified exceptions, such as explaining an input problem, releasing a resource or passing the failure to a caller.

This common SL/HL lesson uses Python examples and includes the Java try/catch/finally syntax required by the syllabus. We will distinguish unexpected inputs, unavailable resources and logic errors, then trace what actually runs when an exception occurs.

02 | THREE IMPORTANT SOURCES OF FAILURE

Source Example Appropriate response
Unexpected input int("three") cannot produce an integer. Catch the relevant conversion exception and give a meaningful response.
Resource unavailability A required file is missing or permission is denied. Handle the relevant failure, release acquired resources and report or propagate the problem.
Logic error A total is overwritten rather than accumulated. Use tests and debugging to find and correct the algorithm; there may be no exception to catch.

These categories describe problems, not three separate exception keywords. A bug can cause an exception, but many logic errors produce plausible wrong answers without raising anything. Exception handling supports reliability; it does not establish that the algorithm is correct.

03 | WHAT HAPPENS WITHOUT A HANDLER?

raw = "three"
quantity = int(raw)
print(quantity * 2)

int tries to interpret the text as an integer. Here it raises ValueError. Normal execution stops at that expression, so quantity is not assigned by this failed operation and the following print is not reached.

Python looks for an applicable handler in the current execution context and then in callers. If none handles the exception, it reaches the top level and a traceback is reported. This tells you the exception type and where the failure occurred.

A traceback is evidence for investigation, not a replacement for a suitable response in a finished user-facing program.

04 | THE BASIC PYTHON STRUCTURE

raw = "three"
try:
    quantity = int(raw)
    print(quantity * 2)
except ValueError:
    print("Enter a whole number")

print("Ready for the next task")

The try block contains the operation whose exception you plan to handle. If that block raises ValueError, execution jumps to the matching except block. Remaining statements in the try block are skipped.

The handler prints a useful message. If it finishes normally, execution continues after the whole try statement. It does not jump back to int(raw), and it does not magically supply a valid quantity.

Indentation defines the blocks. The except clause is aligned with try, and its response is indented beneath it.

05 | TRACE SUCCESS AND FAILURE

Input text Route Output
"3" Conversion succeeds; multiplication/print runs; except is skipped. 6, then Ready for the next task
"three" Conversion raises ValueError; remaining try statements are skipped; handler runs. Enter a whole number, then Ready for the next task

Do not execute both routes in one trace. A successful try skips its except handler; a failed conversion does not reach the multiplication.

The response after the try statement depends on variables that actually exist. If later code uses quantity after the failure, it needs a deliberate design to ensure a valid value is available.

06 | DIFFERENT EXCEPTIONS NEED DIFFERENT RESPONSES

raw = "0"
try:
    quantity = int(raw)
    result = 12 / quantity
    print(result)
except ValueError:
    print("Enter a whole number")
except ZeroDivisionError:
    print("Quantity must not be zero")

"0" converts successfully to integer 0. The next operation, division by zero, raises ZeroDivisionError. It does not match ValueError, so Python selects the second handler.

With "three", conversion fails first and the division is never attempted. With "3", the result is 4.0 and neither handler runs.

Catch types that suit the planned response. A conversion message is misleading for a division error even if both interrupt the same calculation.

07 | CATCH SPECIFIC EXCEPTIONS BEFORE GENERAL ONES

try:
    number = int("bad")
except ValueError:
    print("Invalid integer text")
except Exception:
    print("Another ordinary exception occurred")

Python considers handlers in order and selects the first matching one. Exception is a broad base class for ordinary exceptions; putting it first would also catch ValueError and make the later specialised response ineffective.

Use broad handling only at an appropriate boundary with a real response, reporting or re-raising strategy. A blanket “something went wrong” in every function can hide the cause and make debugging harder.

A bare except also catches exceptions outside Exception, such as KeyboardInterrupt, and is usually inappropriate for routine input handling.

08 | VALIDATION AND EXCEPTION HANDLING WORK TOGETHER

raw = "-2"
try:
    quantity = int(raw)
except ValueError:
    print("Enter a whole number")
else:
    if 1 <= quantity <= 10:
        print("Accepted:", quantity)
    else:
        print("Quantity must be from 1 to 10")

Conversion checks whether a suitable integer can be produced. It does not establish that the value meets the business rule. Here −2 is a valid int but is outside the permitted range.

The optional else runs when the try block finishes without an exception. It separates the conversion that might fail from the valid-path processing. This is a Python convenience rather than a requirement to use else in every handler.

Use ordinary conditions for expected choices or range checks. Use exception handling for the failure behaviour of operations that raise exceptions. Neither replaces the other.

09 | RETRY ONLY WHEN THE PROGRAM SAYS TO

while True:
    raw = input("Quantity from 1 to 10: ")
    try:
        quantity = int(raw)
    except ValueError:
        print("Enter a whole number")
        continue

    if 1 <= quantity <= 10:
        break
    print("Quantity must be from 1 to 10")

print("Accepted:", quantity)

The loop supplies the retry. continue starts another iteration after invalid integer text. A valid in-range quantity reaches break and leaves the loop. A valid integer outside the range reaches the range message, then the loop repeats.

An except block alone does not repeat anything. Decide whether retrying is useful and whether users need a cancellation route. For remote resources, uncontrolled immediate retries can waste time and add load; define limits and a sensible response.

10 | RESOURCE UNAVAILABILITY IS NOT INVALID TEXT

Programs depend on files, connections and services. A path can be wrong, a file can disappear, permission can be denied, or a remote service can time out. These problems can occur even when user input has the correct format.

A response might offer a new path, use an explicitly permitted fallback, ask the caller to retry later or stop the operation safely. The correct choice depends on what the operation promises.

Do not print “Saved successfully” after a failed save, or replace unavailable data with invented results that look genuine. A handler should preserve an honest outcome.

11 | READ A FILE WITH SPECIFIC HANDLERS

try:
    with open("workshop.txt", "r", encoding="utf-8") as file:
        content = file.read()
except FileNotFoundError:
    print("The workshop file is missing")
except PermissionError:
    print("You do not have permission to read that file")
else:
    print(content)

FileNotFoundError and PermissionError need different explanations. Other failures are still possible, such as a decoding error or a different I/O error; this sample does not claim to handle every resource failure.

The with statement manages a successfully opened file and closes it when its block exits, including ordinary exception unwinding. If opening fails, no file handle was acquired by this statement.

The else keeps the success output off the failure path. Catching an error does not itself recreate the missing file or grant permission.

12 | FINALLY: A CLEANUP ROUTE

raw = "three"
try:
    quantity = int(raw)
    print(quantity)
except ValueError:
    print("Invalid number")
finally:
    print("Attempt finished")

print("Continue")

finally runs when control leaves the try construct through ordinary execution or exception unwinding, whether the try succeeded or a handler ran. It is commonly used for cleanup that must happen on those routes.

Here the output is Invalid number, Attempt finished, then Continue. With raw = "3", it is 3, Attempt finished, then Continue. The final message is not itself recovery; it simply shows that the finally route was reached.

Do not interpret “finally runs” as a guarantee after a power failure, forced process termination or other abrupt shutdown that prevents Python executing cleanup.

13 | UNMATCHED EXCEPTIONS STILL UNWIND THROUGH FINALLY

raw = None
try:
    quantity = int(raw)
except ValueError:
    print("Enter a whole number")
finally:
    print("Attempt finished")

print("Continue")

None models an absent value supplied by another part of a program, not the result of Python input(), which normally returns str. int(None) raises TypeError, and the ValueError handler does not match it.

The finally block runs during unwinding and prints Attempt finished. The exception then continues to a caller or the top level. The final print("Continue") is not reached unless a suitable outer structure catches the exception and chooses its own continuation.

finally does not swallow an unmatched exception just by being present.

14 | CLEAN UP ONLY WHAT WAS ACQUIRED

file = None
try:
    file = open("workshop.txt", "r", encoding="utf-8")
    print(file.read())
except OSError:
    print("The file operation failed")
finally:
    if file is not None:
        file.close()

Initialising file to None lets the cleanup check whether opening actually succeeded. If open raises before assignment, calling file.close() unconditionally would create another error.

OSError covers these general file-operation failures, but not every possible exception such as invalid text decoding. The finally still closes a successfully acquired file during ordinary unwinding of another error.

In normal Python file-reading code, prefer with for this resource lifetime. The explicit version shows what cleanup responsibility means and why failed acquisition must be considered. Cleanup itself can also fail; a larger application needs an appropriate policy.

15 | DO NOT MASK THE ORIGINAL OUTCOME

A handler that does nothing can leave the program in an invalid state. A finally block that returns a value or raises a new exception can also replace a pending return or obscure an earlier failure.

Keep cleanup focused on releasing or restoring resources. Avoid returning from finally to force a success result. If a lower-level function cannot resolve a failure, it can let the exception propagate or use raise within a handler to re-raise the current exception.

Logging or reporting should preserve useful diagnostic context. Tell users what they can do, while keeping sensitive internal details out of public messages.

16 | LOGIC ERRORS MAY RAISE NOTHING

values = [4, 7]
total = 0
for number in values:
    total = number  # wrong for a running total
print(total)  # 7, but the required sum is 11

Every operation is valid Python, so no exception is raised. Wrapping this code in try/except does not reveal that it violates the required sum. The algorithm must use total = total + number.

A different logic bug might cause an exception, such as using a wrong position to access a list. Catching IndexError can control the failure route, but does not correct the faulty index calculation.

Use expected results, trace tables and debugging to investigate the first incorrect state. Exception handling and debugging have related but different roles.

17 | SYNTAX ERRORS ARE ANOTHER CATEGORY

A missing colon or invalid indentation can prevent code from being parsed. An ordinary handler in that same invalid source cannot run because the program never reaches its runtime try statement.

This differs from int("three"), which is syntactically valid but raises an exception while executing. When describing a failure, identify when it occurs and whether the displayed handler could actually catch it.

Special cases involving code compiled dynamically exist, but the ordinary beginner workflow is to correct syntax first, then test runtime behaviour and logic.

18 | JAVA: TRY, CATCH AND FINALLY

public class ExceptionDemo {
    public static void main(String[] args) {
        String raw = "three";
        try {
            int quantity = Integer.parseInt(raw);
            int result = 12 / quantity;
            System.out.println(result);
        } catch (NumberFormatException error) {
            System.out.println("Enter a whole number");
        } catch (ArithmeticException error) {
            System.out.println("Quantity must not be zero");
        } finally {
            System.out.println("Attempt finished");
        }
        System.out.println("Continue");
    }
}

Java uses catch where Python uses except, and braces rather than indentation to delimit these blocks. Integer.parseInt can raise NumberFormatException for unsuitable text. Java throws an exception; Python terminology usually says raises.

This example uses integer division, so raw = "3" outputs 4; raw = "0" causes ArithmeticException. Do not generalise the zero rule to Java floating-point division, which can produce infinity or NaN instead of that exception.

The finally route serves a similar cleanup purpose. As in Python, unmatched exceptions can continue outward after finally; this does not guarantee that the statement after the construct will run.

19 | COMPARE THE LANGUAGE STRUCTURES

Purpose Python Java
Protected operation try: followed by indented statements try { statements }
Specific handler except ValueError: catch (NumberFormatException error) { ... }
Division example 12 / 0 raises ZeroDivisionError Integer 12 / 0 throws ArithmeticException
Cleanup finally: finally { ... }
Deliberately signal an exception raise ValueError("message") throw new IllegalArgumentException("message");

Types and language rules are not interchangeable even when the overall control-flow idea is similar. The syllabus asks for familiarity with both try/except and try/catch; the worked language comparison helps you read either structure.

20 | INTERACTIVE: WHICH LINES ACTUALLY RUN?

Choose a supplied Python scenario, then predict and execute each action. The same handler structure is used throughout. The absent-value case supplies None to demonstrate a TypeError that is not caught by these two handlers. The display is a bounded trace of these examples, not a general Python runner.

Executed actions, state and control flow
Action Current values Route / explanation

21 | FOLLOW FOUR DIFFERENT ROUTES

Scenario What fails? Handler Finally? / after construct?
"3" Nothing None Finally, then Continue
"three" int conversion ValueError Finally, then Continue
"0" Division ZeroDivisionError Finally, then Continue
None int conversion raises TypeError No match Finally, then propagation; no Continue here

The first failing operation determines the route. Once an exception is raised, do not execute later statements in the abandoned try block. A handler does not restart that block.

Successful recovery must leave enough valid state for subsequent work. Do not use a result after a failure path on which it was never assigned.

22 | WORKED PROGRAM: A SAFE RATIO

def show_ratio(raw_total, raw_count):
    try:
        total = int(raw_total)
        count = int(raw_count)
    except ValueError:
        print("Use whole-number text")
        return

    if count <= 0:
        print("Count must be positive")
        return

    print("Ratio:", total / count)

show_ratio("12", "3")
show_ratio("twelve", "3")
show_ratio("12", "0")

The outputs are Ratio: 4.0, Use whole-number text, and Count must be positive. Specific conversion handling and a business-rule condition work together. Early returns prevent the invalid paths reaching division.

Assume the supplied arguments are strings for this example. The function does not claim to handle every type of caller error or to validate the wider meaning of total.

23 | CONSTRUCT AND TEST A RECOVERY ROUTE

Write a function that receives text for a whole-number book count. Catch invalid integer text and show a useful message. If conversion succeeds, require a count from 0 to 20; print twice that count only when it is in range. Add finally to print Attempt checked once.

Test "4", "four", "-1" and "21". Predict which paths produce a doubled count and whether the final message appears.

Reveal one possible solution
def check_books(raw):
    try:
        books = int(raw)
        if 0 <= books <= 20:
            print("Points:", books * 2)
        else:
            print("Count must be from 0 to 20")
    except ValueError:
        print("Enter a whole number")
    finally:
        print("Attempt checked")

check_books("4")
check_books("four")
check_books("-1")
check_books("21")

Only "4" produces Points: 8. Each call prints Attempt checked once. A finally message demonstrates control flow here; in a real resource operation, its main purpose would normally be cleanup rather than a success claim.

24 | COMMON MISTAKES

Mistake Correction
except repeats the input automatically A loop or explicit retry supplies repetition.
finally means the error was handled It can run before an unmatched exception propagates.
Any handler catches every exception The type must match; first matching handler is chosen.
A valid integer is automatically valid input Range and other problem rules still need checking.
try fixes a wrong formula Many logic errors raise nothing and need debugging.
Cleanup can always close the file Check acquisition or use with; opening may have failed.
The line after try always runs It is skipped if an exception continues outward.
A broad handler is always safer It can conceal unexpected defects and invalid state.

25 | DESCRIBE A TECHNIQUE WITH ITS EFFECT

For describe, give a detailed account: identify the possible failure, the operation in try, the matching handler and its response, and what happens afterwards. Include the role of finally where applicable.

For a file task, say how resource acquisition and cleanup are managed. For a logic error, explain whether an exception occurs at all and why testing/debugging remains necessary.

Trace expected success, expected handled failures and at least one relevant unhandled or boundary case. A program that does not crash in one test is not thereby correct.

26 | YOUR NEXT STEP

You can now follow normal execution, specific handlers, cleanup and propagation, read the corresponding Python and Java structures, and distinguish controlled error response from fixing a bug.

The next lesson introduces common debugging techniques to locate the cause of incorrect behaviour, including failures that raise no exception.

MATCH THE EXCEPTION-HANDLING IDEA

Terminology

Terminology

Exception

A runtime event represented by an exception object that interrupts normal execution.

Exception handling

A controlled response to specified exceptions.

try block

Statements whose raised exceptions may be handled by associated handlers.

except clause

Python syntax specifying an exception handler.

catch block

Java syntax specifying an exception handler.

finally block

A block run when leaving the construct through ordinary control flow or exception unwinding, often for cleanup.

Handler

Code selected to respond to a matching exception.

Raise

Signal an exception in Python.

Throw

Signal an exception in Java.

Propagation

An unhandled exception continuing outward in search of a handler.

Traceback

Python diagnostic information showing the failure and relevant call locations.

ValueError

A Python exception for an operation receiving an unsuitable value of an otherwise appropriate type.

TypeError

A Python exception for an unsupported operation or unsuitable type.

ZeroDivisionError

A Python exception for division or modulo by zero.

FileNotFoundError

A Python exception for a requested file/path that cannot be found.

PermissionError

A Python exception for an operation denied by access permissions.

OSError

A Python exception family for operating-system-related failures, including many file operations.

NumberFormatException

A Java exception such as an invalid integer-text conversion failure.

ArithmeticException

A Java exception for arithmetic failures such as integer division by zero.

Resource

An external facility or handle used by a program, such as an opened file or connection.

Acquisition

Successfully obtaining a resource that may need release.

Cleanup

Releasing acquired resources or restoring required state.

Context manager

A Python protocol used by with to manage entry and exit, such as closing a file.

Validation

Checking whether input meets the problem’s acceptance rules.

Logic error

An incorrect algorithm or operation that can produce wrong results without an exception.

Syntax error

Invalid source structure that normally prevents that code being parsed/executed.

Retry

An explicit attempt to perform an operation again under a defined policy.

Specific handler

A handler targeted at a relevant exception type.

Re-raise

Raise the currently handled exception again so it continues outward.

Recovery

A defined response that restores a usable state or allows an appropriate alternative outcome.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which distinguish failures accurately?
2. Which occur after int("three") raises ValueError in a matching try?
3. Which describe successful try execution?
4. Which describe the zero scenario?
5. Which explain finally?
6. Which support resource handling?
7. Which describe validation?
8. Which compare the language examples accurately?
9. Which help avoid concealed defects?
10. Which describe the absent-value scenario?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Describe the role of exception handling in a program.

2. Describe the Python try/except structure using invalid numeric input.

3. Trace the valid and invalid-text scenarios in the interactive example.

4. Describe why zero requires a different handler from unsuitable text.

5. Describe how finally differs from except.

6. Trace the unmatched None scenario.

7. Describe a suitable response to a missing or inaccessible file.

8. Explain why a file variable is initialised to None before manual cleanup.

9. Describe the Java exception-handling example.

10. Explain why overwriting a running total is not necessarily caught by except.

11. Describe how to combine conversion handling with range validation.

12. Describe tests for a robust small input routine.

DESCRIBE IT | A GROUP-SIZE CALCULATION

A program reads text for a group size and divides 24 by that number. Describe which operations belong in try, the specific handlers for invalid integer text and division by zero, an appropriate positive-range check, and the role of finally. Explain why a wrong numerator such as 42 instead of 24 may still require debugging even if no exception is raised.

Reveal an answer outline

Use ValueError for unsuitable integer text and ZeroDivisionError if division by zero is allowed to reach the operation. A positive-range condition can reject zero and negative values before division instead. Provide accurate messages without using an unassigned result. Finally manages cleanup on ordinary exit and unwinding; it does not repair a wrong numerator, which is a logic error detectable with expected results and tracing.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

Selections are kept while this page is open.

Workbook

Workbook

COMING SOON

The workbook for B2.1.3 Exception Handling is coming soon. Complete the matching task and written questions in your exercise book.