Using raise to Enforce Input Rules

A function can receive an argument that Python can process but that your program should reject. A task count of zero, for example, is an integer, yet it is unsuitable for calculating time per task. In Python 3, you can explicitly signal this failure instead of producing a misleading result. The central decision is where normal processing should stop and what information the failure should carry.

Turn a requirement into a check

Validation means checking whether input satisfies the requirements for an operation. Write those requirements before writing the calculation. Suppose a scheduling function accepts a nonnegative number of minutes and an integer task count. Its calculation requires a positive task count:


minutes per task=total minutestasks,tasks>0.\text{minutes per task}=\frac{\text{total minutes}}{\text{tasks}},\qquad \text{tasks}>0.


Raising an exception means explicitly signalling an exceptional condition so that ordinary execution is interrupted. For an unacceptable argument value, ValueError is a suitable choice here.


Python
def minutes_per_task(total_minutes, tasks):
    if tasks <= 0:
        raise ValueError("tasks must be greater than zero")
    return total_minutes / tasks


The condition identifies invalid input. Its indented statement runs only when that condition is true. Check the requirement before performing the operation that depends on it.



Build a useful raise statement

The statement has three useful pieces: the keyword raise, an exception type, and a message supplied when creating the exception object.


Python
raise ValueError("tasks must be greater than zero")


Here, ValueError(...) creates an instance containing the message. The keyword raise signals it. Creating the object alone does not raise it.


Choose a message that identifies the rejected input and the requirement it violated. A message such as "bad input" gives little direction. A message such as "tasks must be greater than zero" explains what the caller should change. Keep the message consistent with the actual condition: a check rejecting zero should not claim that only negative values are invalid.


Example: Calling minutes_per_task(45, 3) returns 15.0, representing 15 minutes per task. Calling minutes_per_task(45, 0) raises ValueError before division occurs. Both outcomes follow from the same check; the argument determines which path runs.

Understand what raising changes


A validation decision branches toward raising an exception or continuing computation.


When this function raises, execution does not simply move to its next statement. The function produces no normal return value for that call. The exception can travel back to the calling code; if nothing handles it, execution ends with an error report. Deciding how to handle that signal is a separate task.


Statement

Effect when reached

raise ValueError("invalid count")

Signals an exception and interrupts ordinary execution.

return ValueError("invalid count")

Ends the function normally by returning an exception object.

print("invalid count")

Displays text, then permits subsequent statements to run.

ValueError("invalid count")

Creates an exception object without signalling it.



This distinction matters when a function updates a list, saves a booking, or changes an account balance. A useful failure message does not replace a correctly positioned check. Put rejection checks before work that should happen only for accepted input.

What to remember

  • Use raise to signal a failure explicitly.
  • Give the exception a clear, accurate message.
  • A raised exception interrupts the ordinary path and produces no normal return value for that call.
  • Validate before calculations or stored changes that require acceptable input.

Example: Rejecting Impossible Seat Requests

A small theatre has 18 seats available. Its reservation calculator receives integer seat counts and uses this function to calculate how many seats would remain. The function does not change stored bookings.


Python
def remaining_seats(requested, available):
    if requested <= 0:
        raise ValueError("requested must be positive")
    if requested > available:
        raise ValueError("requested exceeds available")
    return available - requested


A guard clause is an early conditional check that leaves the normal processing path when a requirement fails. Here, each guard uses raise. Both checks come before the calculation that assumes an acceptable request.

A valid request

a) Determine the result of remaining_seats(6, 18) and explain which checks run.

  1. Substitute 6 for requested and 18 for available. The first condition, 6 <= 0, evaluates to ________, so its raising statement is skipped.
  2. The second condition, 6 > 18, evaluates to ________. This raising statement is also skipped, allowing the return statement to run.
  3. Calculate the remaining seats:


18−6=12 seats.18-6=12\text{ seats}.


The function returns 12, representing 12 remaining seats. Passing both checks allows a normal numeric result.

A nonpositive request

b) Determine what happens for remaining_seats(0, 18). State the exception type and message.

  1. Substitute 0 into the first condition. The comparison 0 <= 0 evaluates to ________, so execution enters that conditional block.
  2. Python creates a ValueError object carrying the message "requested must be positive". The raise keyword signals that exception immediately.
  3. The second check and the final subtraction are not reached. Although subtracting zero would be mathematically possible, the stated booking rule rejects this request before calculation.

The call raises ValueError with the message "requested must be positive". It does not return a remaining-seat count.

An excessive request

c) Determine what happens for remaining_seats(22, 18). Identify the check that interrupts execution.

  1. Evaluate the first condition. The comparison 22 <= 0 is ________, so a positive request passes this check.
  2. Evaluate the second condition. The comparison 22 > 18 is ________, so Python executes its raising statement.
  3. The request exceeds the 18 available seats. The function signals this failure before subtraction, preventing a negative seat count from being returned as though the reservation were acceptable.

The second guard interrupts execution. The call raises ValueError with the message "requested exceeds available" and produces no normal return value.

A Python function has detected an invalid booking quantity. Which statement explicitly signals a failure rather than merely creating, displaying, or returning an exception object?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A Python file-export tool prepares an exception object when the destination folder is unavailable. Complete the replacement statement below so the function signals this failure using the stored object.


Python
def require_destination(folder_available):
    if not folder_available:
        problem = ValueError("Destination folder is unavailable")
        # Replace this comment with the completed statement.
    return "Destination ready"


The replacement statement is problem.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A museum sells between 1 and 24 passes per order, inclusive, at 6 dollars per pass. Its Python function receives an integer:


Python
def order_cost(passes):
    if passes < 1 or passes > 24:
        raise ValueError("passes must be from 1 to 24")
    return passes * 6


Complete each row for an independent call. Enter the exact integer return value in dollars, or enter ValueError if the function raises that exception.

Passes requestedReturn value (dollars) or exception name
0
1
12
24
25

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice