Python raise Keyword

Example

If x is less than 0, an error is raised and the program stops:

x = -1
if x < 0:
  raise Exception("Sorry, no numbers below zero")

Run Instance

Definition and Usage

The raise keyword is used to raise exceptions.

You can define the type of error to be raised and the text to be printed to the user.

More Examples

Example

If x is not an integer, a TypeError is raised:

x = "hello"
if not type(x) is int:
  raise TypeError("Only integers are allowed")

Run Instance