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?
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?
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()