It is useful sometimes to catch an exception and then re-raise it or raise a different one.
This can be done using the raise ... from statement.
try:
# Code that might raise an exception
except ExceptionType as e:
# Code that handles the exception
raise ExceptionType2("Message") from eThe above code will raise an exception of type ExceptionType2 with the message Message and the original exception will be stored in the __cause__ attribute of the new exception.
By default, the nested raised exception gets chained to the new exception so in our case the from e part is optional.
But if you want to raise a new exception and not chain the nested one, you can use the from None statement.
try:
# Code that might raise an exception
except ExceptionType as e:
# Code that handles the exception
raise ExceptionType2("Message") from NoneNote: It is recommended to always chain exceptions, unless you have a good reason not to.
Note 2: Re-raising an exception inside an
exceptstatement is usually a bad practice. But it can be useful sometimes, for example when you want to add more information to the exception.