0
0
Pythonprogramming~10 mins

Raising exceptions in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to raise a ValueError with a message.

Python
def check_positive(number):
    if number <= 0:
        raise [1]("Number must be positive")
Drag options to blanks, or click blank then click option'
AValueError
Bprint
Creturn
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using print instead of raise
Using return instead of raise
Raising a generic Exception instead of ValueError
2fill in blank
medium

Complete the code to raise a custom exception with a message.

Python
class MyError(Exception):
    pass

def test():
    raise [1]("This is a custom error")
Drag options to blanks, or click blank then click option'
AMyError
BTypeError
CValueError
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Raising a built-in exception instead of the custom one
Forgetting to define the custom exception class
Using the wrong exception class name
3fill in blank
hard

Fix the error in raising an exception with a message.

Python
def check_age(age):
    if age < 18:
        raise ValueError[1]"Age must be at least 18"
Drag options to blanks, or click blank then click option'
A:
B,
C[
D(
Attempts:
3 left
💡 Hint
Common Mistakes
Using a comma instead of parentheses
Using a colon or bracket instead of parentheses
Not enclosing the message in quotes
4fill in blank
hard

Fill both blanks to raise a TypeError with a custom message.

Python
def check_string(value):
    if not isinstance(value, str):
        raise [1]([2])
Drag options to blanks, or click blank then click option'
ATypeError
B"Value must be a string"
C"Invalid type"
DValueError
Attempts:
3 left
💡 Hint
Common Mistakes
Using ValueError instead of TypeError
Not putting the message inside parentheses
Using a variable instead of a string message
5fill in blank
hard

Fill all three blanks to raise a RuntimeError with a formatted message including a variable.

Python
def check_status(status):
    if status != 'ok':
        raise [1](f"Status is [2] but expected [3]")
Drag options to blanks, or click blank then click option'
ARuntimeError
Bstatus
C'ok'
DValueError
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception type
Not using f-string syntax correctly
Forgetting to include the variable in the message