raise — Python Technical Interview Questions & Answers

raise

raise

  • raise throws an error when your rule is broken. if age < 0: raise ValueError("age cannot be negative"). The caller can except it. Use a clear message. You can raise built-in types or a small custom class. This is how a function refuses bad input instead of returning a magic -1.
  • Tiny validation + raise ValueError is the fresher pattern. Don’t raise Exception("error") for everything — name the type.
  • Output: amount must be > 0. raise stops the function; except prints the message.
  try:  10 / 0
         │ ZeroDivisionError
         ▼
  except → Cannot divide
         │
         ▼
      finally

Technical Interview Tip: if age < 0: raise ValueError(...).

Code Examples for raise

Example

# raise
def deposit(amt):
    if amt <= 0:
        raise ValueError("amount must be > 0")
    return amt

try:
    deposit(-10)
except ValueError as e:
    print(e)

Output: amount must be > 0. raise stops the function; except prints the message.

How to Explain raise to an Interviewer

Explain raise as if you are teaching a junior — definition, then one tiny script.

raise Error("msg"). Validate early.

What does the example print, and why?

amount must be > 0

What mistake do freshers make with raise?

raise Error("msg").