Bird
Raised Fist0
Pythonprogramming~10 mins

Raising exceptions in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Raising exceptions
Start
Check condition
Yes
Raise exception
Exception propagates
Handle exception or crash
No
Continue normal flow
End
The program checks a condition, raises an exception if true, then the exception moves up until handled or program stops.
Execution Sample
Python
def check_age(age):
    if age < 18:
        raise ValueError("Too young")
    return "Allowed"
This function raises a ValueError if age is less than 18, otherwise returns 'Allowed'.
Execution Table
StepActionConditionResultOutput/Exception
1Call check_age(16)age < 18?16 < 18 is TrueRaise ValueError('Too young')
2Exception propagatesNo further code runsException not caught hereValueError('Too young')
3Call check_age(20)age < 18?20 < 18 is FalseReturn 'Allowed'
💡 Execution stops at exception if not caught; otherwise continues normally.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
ageN/A162020
Key Moments - 3 Insights
Why does the function stop running after raising the exception?
When the exception is raised (see Step 1 in execution_table), the function immediately stops and does not run the return statement.
What happens if the exception is not caught?
The exception moves up the call stack and if no code catches it, the program stops with an error (Step 2).
Why does check_age(20) return 'Allowed'?
Because the condition age < 18 is false (Step 3), so no exception is raised and the function returns normally.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at Step 1 when age is 16?
AThe function returns 'Allowed'
BThe function raises a ValueError
CThe function continues without any action
DThe function prints 'Too young'
💡 Hint
Check the 'Output/Exception' column at Step 1 in execution_table.
At which step does the function return a normal value instead of raising an exception?
AStep 3
BStep 1
CStep 2
DNone
💡 Hint
Look for the row where 'Output/Exception' shows a return value in execution_table.
If we change the age to 18, what would happen according to the execution_table logic?
ARaise ValueError
BRaise a different exception
CReturn 'Allowed'
DFunction does nothing
💡 Hint
Check the condition 'age < 18' and what happens when it is false in execution_table.
Concept Snapshot
Raising exceptions:
Use 'raise ExceptionType("message")' to stop normal flow.
Exception moves up until caught or program stops.
If condition triggers, raise exception.
Otherwise, continue normal execution.
Full Transcript
This visual execution shows how raising exceptions works in Python. The function check_age checks if age is less than 18. If yes, it raises a ValueError and stops running. The exception moves up until caught or program ends with error. If age is 20, no exception is raised and function returns 'Allowed'. This helps stop wrong inputs and handle errors clearly.

Practice

(1/5)
1. What does the raise statement do in Python?
easy
A. It creates a new variable.
B. It prints a message to the screen.
C. It stops the program and signals an error.
D. It repeats a block of code.

Solution

  1. Step 1: Understand the purpose of raise

    The raise statement is used to stop the program when an error or unexpected situation occurs.
  2. Step 2: Compare options with raise behavior

    Only It stops the program and signals an error. correctly describes that raise stops the program and signals an error.
  3. Final Answer:

    It stops the program and signals an error. -> Option C
  4. Quick Check:

    raise = stop program on error [OK]
Hint: Remember: raise means stop and show error [OK]
Common Mistakes:
  • Thinking raise prints messages
  • Confusing raise with variable creation
  • Assuming raise repeats code
2. Which of the following is the correct syntax to raise a ValueError with a message "Invalid input"?
easy
A. raise ValueError("Invalid input")
B. throw ValueError("Invalid input")
C. raise new ValueError("Invalid input")
D. error ValueError("Invalid input")

Solution

  1. Step 1: Recall Python syntax for raising exceptions

    In Python, the correct way to raise an exception is using raise ExceptionType("message").
  2. Step 2: Check each option

    raise ValueError("Invalid input") uses correct syntax. Options B, C, and D use invalid keywords or extra words not used in Python.
  3. Final Answer:

    raise ValueError("Invalid input") -> Option A
  4. Quick Check:

    raise + ExceptionType + message = correct syntax [OK]
Hint: Use 'raise ExceptionType("message")' exactly [OK]
Common Mistakes:
  • Using 'throw' instead of 'raise'
  • Adding 'new' keyword like other languages
  • Using 'error' keyword which doesn't exist
3. What will be the output of this code?
def check_age(age):
    if age < 18:
        raise ValueError("Too young")
    return "Access granted"

try:
    print(check_age(16))
except ValueError as e:
    print(e)
medium
A. Too young
B. Access granted
C. ValueError exception not caught
D. No output

Solution

  1. Step 1: Analyze function behavior with age 16

    Since 16 < 18, the function raises a ValueError with message "Too young".
  2. Step 2: Check exception handling in try-except

    The exception is caught by the except block, which prints the error message "Too young".
  3. Final Answer:

    Too young -> Option A
  4. Quick Check:

    Exception message printed = Too young [OK]
Hint: Exception message prints if caught in except [OK]
Common Mistakes:
  • Assuming function returns 'Access granted'
  • Thinking exception crashes program
  • Missing that except prints the error message
4. Find the error in this code snippet:
def divide(a, b):
    if b == 0:
        raise "Cannot divide by zero"
    return a / b

print(divide(10, 0))
medium
A. No error, code runs fine
B. raise must be followed by an exception instance, not a string
C. Division by zero is allowed in Python
D. Function divide should return None when b is zero

Solution

  1. Step 1: Identify the raise statement usage

    The code uses raise "Cannot divide by zero", which raises a string, not an exception object.
  2. Step 2: Understand correct raise syntax

    Python requires raising an exception instance, e.g., raise ValueError("Cannot divide by zero").
  3. Final Answer:

    raise must be followed by an exception instance, not a string -> Option B
  4. Quick Check:

    raise needs exception object, not string [OK]
Hint: Always raise an exception object, not a string [OK]
Common Mistakes:
  • Raising strings instead of exceptions
  • Ignoring that division by zero causes error
  • Assuming code runs without error
5. You want to create a function check_score(score) that raises a ValueError if the score is not between 0 and 100 (inclusive). Which code correctly implements this?
hard
A. def check_score(score): if score <= 0 or score >= 100: raise ValueError("Score must be 0-100") return True
B. def check_score(score): if 0 < score < 100: raise ValueError("Score must be 0-100") return True
C. def check_score(score): if score == 0 or score == 100: raise ValueError("Score must be 0-100") return True
D. def check_score(score): if score < 0 or score > 100: raise ValueError("Score must be 0-100") return True

Solution

  1. Step 1: Understand the valid score range

    Score must be between 0 and 100, including 0 and 100.
  2. Step 2: Check each condition for raising ValueError

    def check_score(score): if score < 0 or score > 100: raise ValueError("Score must be 0-100") return True raises error if score is less than 0 or greater than 100, correctly allowing 0 and 100.
  3. Step 3: Verify other options

    def check_score(score): if 0 < score < 100: raise ValueError("Score must be 0-100") return True raises error incorrectly for valid scores between 0 and 100. def check_score(score): if score <= 0 or score >= 100: raise ValueError("Score must be 0-100") return True excludes 0 and 100 incorrectly. def check_score(score): if score == 0 or score == 100: raise ValueError("Score must be 0-100") return True raises error only if score equals 0 or 100, which is wrong.
  4. Final Answer:

    def check_score(score): if score < 0 or score > 100: raise ValueError("Score must be 0-100") return True -> Option D
  5. Quick Check:

    Raise error outside 0-100 inclusive = def check_score(score): if score < 0 or score > 100: raise ValueError("Score must be 0-100") return True [OK]
Hint: Use 'if score < 0 or score > 100' to check range [OK]
Common Mistakes:
  • Using wrong comparison operators
  • Excluding valid boundary values
  • Raising error inside valid range