PythonSyntax and keywords
raise
Raises an exception, signaling an error or a disallowed situation.
Example
#Python
def set_level(level):
if not isinstance(level, int):
raise TypeError("Level must be an integer")
if level < 1:
raise ValueError(f"Level must be positive, got {level}")
return level
for value in [5, 0, "3"]:
try:
print("Level set to", set_level(value))
except (TypeError, ValueError) as error:
print("Error:", error)Resultsaved result, you can check it
Level set to 5
Error: Level must be positive, got 0
Error: Level must be an integer
Definition and usage
#The raise statement raises an exception and interrupts the current action. Control passes to the nearest except block that handles that exception type. If there is none, the program stops with an error message.
Raise an exception when a function receives data it cannot sensibly work with, for example a negative number of points. Built-in types, like ValueError or TypeError, fit most situations.
You create your own exceptions by inheriting from Exception. The notation raise NewError(...) from error preserves information about the original cause, which makes debugging easier.
Syntax
#Syntax
raise ExceptionType("message")More examples
#Python
class OutOfFuelError(Exception):
pass
def start_lesson(fuel):
if fuel <= 0:
raise OutOfFuelError("No fuel for the next lesson")
return fuel - 1
try:
start_lesson(0)
except OutOfFuelError as error:
print(type(error).__name__, "-", error)Resultsaved result, you can check it
OutOfFuelError - No fuel for the next lesson
Good practices
#- An exception message should say what went wrong and what value caused it.
- Name your own exceptions with an
Errorsuffix, e.g.InvalidAnswerError.
Related entries
#- try, except, else, finallyException handling: catching errors without stopping the program.
- assertChecks an assumption in the code and raises AssertionError when it does not hold.
- classDefines a class: a template for objects that combines data with the functions that act on it.
- isinstance()Checks whether an object is of a given type, or of a subtype of it.
Spotted a mistake or missing an example? Write to us.