Difference between “raise” and “raise e”?

There is a difference in the backtraces that the two forms generate. The difference is different in Python 2 and 3.

Using raise:

try:
   int("hello")
except ValueError as e:
   raise

The code gives the following backtrace in Python 2 or Python 3:

Traceback (most recent call last):
  File "myfile.py", line 2, in <module>
    int("hello")
ValueError: invalid literal for int() with base 10: 'hello'

Using raise e:

try:
   int("hello")
except ValueError as e:
   raise e

The code gives the following backtrace in Python 2:

Traceback (most recent call last):
  File "myfile.py", line 4, in <module>
    raise e
ValueError: invalid literal for int() with base 10: 'hello'

The code gives the following backtrace in Python 3:

Traceback (most recent call last):
  File "myfile.py", line 4, in <module>
    raise e
  File "myfile.py", line 2, in <module>
    int("hello")
ValueError: invalid literal for int() with base 10: 'hello'

In Python 2:

In the raise case, the original source of the exception is quoted in the backtrace. In the raise e case, the traceback references the raise e line not the original cause. Therefore, I recommend always using raise rather than raise e.

In Python 3:

The original source of the exception is always quoted. The difference is whether the raise/raise e line is also quoted. It depends on one’s taste and the context of the raise.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)