CodeBlanks Logo Icon CodeBlanks

raise

Learn to raise exceptions with raise.

Raise errors with raise

The raise keyword throws an error. You use it to stop the program when you detect an invalid situation:

age = -5
if age < 0:
    raise ValueError("Geçersiz yaş")

Here a negative age is an error; raise ValueError stops the program and shows the message. The code that raises is raise; the code that catches is try/except.

This is the standard way for functions to report invalid input.

When to use raise

raise is used in two common situations. First, when a function receives an invalid argument. Second, when a precondition is not met:

def set_age(age):
    if age < 0:
        raise ValueError("Negatif yaş")
    return age

This function raises ValueError when given a negative age. The calling code can catch it with try/except. Otherwise the program stops.

This is a core tool for defensive programming.

Practice Raise ValueError on negative age

Assign age = -5. Inside an if age < 0: block write raise ValueError("Geçersiz yaş"). Below it write print("yaş: " + str(age)). Wrap everything in try/except ValueError and in the except block write print("Geçersiz yaş").

Starter code

main.py
# assign a negative age value
# if negative, raise ValueError
# catch with try/except and print message

Sample solution

main.py
try:
    age = -5
    if age < 0:
        raise ValueError("Geçersiz yaş")
except ValueError:
    print("Geçersiz yaş")

Expected output

Geçersiz yaş

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match raise concepts

Term Meaning
raise Throws an error
ValueError Error type
if age < 0 Condition
"Geçersiz yaş" Error message

2 Which can be raised with raise?

  • Only ValueError
  • Only strings
  • Only TypeError
  • Exception subclasses Correct answer

Explanation: Any subclass of Exception can be raised with raise.

3 Complete the raise call

Question
if age < 0:
    ____("Geçersiz yaş")
Answer
if age < 0:
    raise ValueError("Geçersiz yaş")

Explanation: raise ValueError("message") raises a ValueError.

All lessons in Beginner