Raising exceptions lets your program stop and show an error when something unexpected happens. It helps you catch problems early and handle them properly.
Raising exceptions in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
raise ExceptionType("Error message")
You use the raise keyword followed by an exception type and an optional message.
The message helps explain what went wrong.
Examples
Python
raise ValueError("Invalid input")
Python
raise RuntimeError("Something went wrong")
Python
raise Exception("Custom error message")
Sample Program
This program checks if the age is valid. If the age is negative, it raises a ValueError. The try-except block catches the error and prints a friendly message.
Python
def check_age(age): if age < 0: raise ValueError("Age cannot be negative") elif age < 18: print("You are a minor.") else: print("You are an adult.") try: check_age(-5) except ValueError as e: print(f"Error: {e}")
Important Notes
Raising exceptions stops the current code and jumps to the nearest error handler.
You can create your own exception classes by inheriting from Exception.
Always provide clear messages to help understand the problem.
Summary
Use raise to stop the program when something goes wrong.
Exceptions help you find and fix errors early.
Catch raised exceptions with try-except to handle errors gracefully.
Practice
1. What does the
raise statement do in Python?easy
Solution
Step 1: Understand the purpose of
Theraiseraisestatement is used to stop the program when an error or unexpected situation occurs.Step 2: Compare options with
Only It stops the program and signals an error. correctly describes thatraisebehaviorraisestops the program and signals an error.Final Answer:
It stops the program and signals an error. -> Option CQuick 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
Solution
Step 1: Recall Python syntax for raising exceptions
In Python, the correct way to raise an exception is usingraise ExceptionType("message").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.Final Answer:
raise ValueError("Invalid input") -> Option AQuick 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
Solution
Step 1: Analyze function behavior with age 16
Since 16 < 18, the function raises a ValueError with message "Too young".Step 2: Check exception handling in try-except
The exception is caught by the except block, which prints the error message "Too young".Final Answer:
Too young -> Option AQuick 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
Solution
Step 1: Identify the raise statement usage
The code usesraise "Cannot divide by zero", which raises a string, not an exception object.Step 2: Understand correct raise syntax
Python requires raising an exception instance, e.g.,raise ValueError("Cannot divide by zero").Final Answer:
raise must be followed by an exception instance, not a string -> Option BQuick 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
Solution
Step 1: Understand the valid score range
Score must be between 0 and 100, including 0 and 100.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.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.Final Answer:
def check_score(score): if score < 0 or score > 100: raise ValueError("Score must be 0-100") return True -> Option DQuick 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
