-1

I've seen people doing both ways but I can't spot the difference between them:

raise Exception('This is the error')

and

raise 'This is the error'

Which one should I use?

Artur Haddad
  • 1,429
  • 2
  • 16
  • 33
  • 1
    `raise 'This is the error'` That doesn't work. Where did you see it? – John Gordon Aug 20 '19 at 20:21
  • 1
    `raise Exception 'This is the error'` That doesn't work either. Perhaps you meant `raise Exception('This is the error')`? – John Gordon Aug 20 '19 at 20:22
  • 1
    Long, long ago, one could raise any value as an exception, but I think that "feature" was eliminated in Python 2.0. – chepner Aug 20 '19 at 20:23
  • The `raise` statement in very old versions of Python was quite different than it is today; e.g., see https://docs.python.org/release/1.5.2p2/ref/raise.html. – chepner Aug 20 '19 at 20:26

1 Answers1

0

Don't use either. The first is a syntax error:

>>> raise Exception "This is an error"
  File "<stdin>", line 1
    raise Exception "This is an error"
                                     ^
SyntaxError: invalid syntax

while the second is a type error (you can't "raise" a str value):

>>> raise "this"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must derive from BaseException

The correct form would be to call the exception type with the error message as an argument:

raise Exception("this is the error")

In the case where the desired exception doesn't require an argument, raising the Exception type itself is equivalent to raising an instance created without an argument.

raise Exception   # equivalent to raise Exception()
chepner
  • 497,756
  • 71
  • 530
  • 681