raise
`raise` stops your code on purpose and throws an error to say something went wrong.
Used in 24 lessons of the course, from 01.05.
raise creates an exception and throws it. Python stops running the current function and climbs up the calls looking for a try / except that catches it. If nobody catches it, the program ends and prints the traceback.
You read it as raise + an exception class + a message in parentheses. For example, raise ValueError("message"). Pick the class that describes the problem: ValueError when the value is wrong, TypeError when the type is.
Why throw an error instead of returning a odd value? Because an error can't be ignored by accident: it forces the caller to decide what to do.
In lesson 01.05 the course uses raise ValueError("simulated provider error") to pretend a provider fails, so you can practice how your code reacts to that failure.
raise ValueError("something failed")
Reach for it when: your code finds a situation it can't resolve, like invalid data, and you want to signal it instead of carrying on with something wrong.
Examples
Common mistake
def check(x):
if x < 0:
raise "negative number"
check(-1)Why: You can only raise exceptions, not a bare string.
How to write it: Use an exception class: raise ValueError("negative number").
