It has two purposes.
jackcogdill has given the first one:
It's used for raising your own errors.
if something: raise Exception('My error!')
The second is to reraise the current exception in an exception handler, so that it can be handled further up the call stack.
try:
generate_exception()
except SomeException as e:
if not can_handle(e):
raise
handle_exception(e)
Answer from Ignacio Vazquez-Abrams on Stack OverflowVideos
It has two purposes.
jackcogdill has given the first one:
It's used for raising your own errors.
if something: raise Exception('My error!')
The second is to reraise the current exception in an exception handler, so that it can be handled further up the call stack.
try:
generate_exception()
except SomeException as e:
if not can_handle(e):
raise
handle_exception(e)
raise without any arguments is a special use of python syntax. It means get the exception and re-raise it. If this usage it could have been called reraise.
raise
From The Python Language Reference:
If no expressions are present, raise re-raises the last exception that was active in the current scope.
If raise is used alone without any argument is strictly used for reraise-ing. If done in the situation that is not at a reraise of another exception, the following error is shown:
RuntimeError: No active exception to reraise
In comparison to try, except, else, and finally blocks, raise statement seems not always needed. I guess it is an optional tool in exception handling that may well be redundant in some scenarios.
For example, these are the two codes with and without use of raise:
Without raise
def check_input(val):
if val < 0:
print("Input must be non-negative")
else:
print(f"Processing value: {val}")
check_input(-10)With raise:
def check_input(val):
if val < 0:
raise ValueError("Input must be non-negative")
print(f"Processing value: {val}")
try:
check_input(-10)
except ValueError as e:
print(f"Error: {e}")Given print function achieving the desired result, not sure if raise statement really needed.