Skip to main content

How to Raise an Exception in Python with raise

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

When a function gets a value it can't work with, the clearest thing it can do is stop and say why. Python's raise statement does that: it creates an exception with your message, ends the function and hands the problem to whoever called it. This guide raises one and catches it, on Python 3.15.2.

Syntax​

Syntax
raise <ExceptionType>("<message>")
PartWhat it means
raiseStops the function at this line and starts the exception
<ExceptionType>The kind of problem, such as ValueError for a value that's the right type but not usable
"<message>"Text that explains the problem. It's shown in the traceback and in str(error)

The Python language reference says raise "evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException."

The Example​

A withdraw function takes money out of a balance. Taking out more than the balance holds raises a ValueError. The script calls it once with a small amount and once with too much, and catches the second one.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

withdraw.py
def withdraw(balance, amount):
if amount > balance:
raise ValueError(f"Cannot withdraw {amount}: the balance is only {balance}")
return balance - amount


print(withdraw(100, 30))

try:
withdraw(100, 250)
except ValueError as error:
print("Refused:", error)

The withdraw.py script in a macOS-style code window: a withdraw function that raises ValueError with a message when the amount is more than the balance, one call that works and one inside try and except ValueError.

Step 2: Run It​

Terminal
uv run python withdraw.py
Output
70
Refused: Cannot withdraw 250: the balance is only 100

The terminal after uv run python withdraw.py: 70, then Refused: Cannot withdraw 250: the balance is only 100.

The first call returned 70. The second one reached raise, so the function stopped there and returned nothing; except ValueError caught the exception and printed its message. The command works unchanged in PowerShell.

When Nobody Catches It​

Without try and except, the exception ends the whole program, and Python prints where it came from. Calling withdraw(100, 250) on its own printed:

Output
Traceback (most recent call last):
File "/Users/you/source/lang-python/probes/p212_uncaught.py", line 7, in <module>
withdraw(100, 250)
~~~~~~~~^^^^^^^^^^
File "/Users/you/source/lang-python/probes/p212_uncaught.py", line 3, in withdraw
raise ValueError(f"Cannot withdraw {amount}: the balance is only {balance}")
ValueError: Cannot withdraw 250: the balance is only 100

The last line is the exception's type and your message. The lines above it show the call that led there, and then the raise line itself.

Common Mistakes​

MistakeWhat happensDo this instead
Raising plain text: raise "Something went wrong"TypeError: exceptions must derive from BaseExceptionRaise an exception with the text: raise ValueError("Something went wrong")
Returning an error value, such as -1, instead of raisingThe caller can use -1 as if it were a real resultRaise, so the problem can't be missed

Troubleshooting​

SymptomLikely causeFix
The program ends with a traceback whose last line is your messageYour exception wasn't caughtCatch it with try and except where you can handle it
except ValueError doesn't catch itA different type was raisedCatch the type named on the traceback's last line

FAQ​

Which exception should I raise?​

The one that describes the problem. For a value that's the right type but can't be used, Python's exceptions reference says ValueError is "Raised when an operation or function receives an argument that has the right type but an inappropriate value".

Can I raise the class without brackets?​

Yes, raise ValueError works. The reference says: "If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments." You lose the message, though, so add one.

Conclusion​

raise ValueError(f"Cannot withdraw {amount}: ...") stopped withdraw at the bad call and carried the reason to the caller, where except ValueError printed it. Raise an exception, not plain text, and give it a message that says what was wrong.

Additional Resources​