views:

235

answers:

3

I want to make an error on purpose so that it would go into the "except":

How do i do that?

+12  A: 

Can't get much more pythonic than this:

raise Exception("I know python!")

See the raise statement docs for python if you'd like more info.

Gabriel Hurley
You forgot this: http://docs.python.org/reference/simple_stmts.html#the-raise-statement
S.Lott
got it. thanks!
Gabriel Hurley
I like your exception text. It makes the person who catches it feel good about himself (or herself).
Chris Lutz
haha, thanks Chris!
Gabriel Hurley
+1  A: 

raise Exception http://www.python.org/dev/peps/pep-3109/

Aly
If you're suggesting this over Gabriel's answer, you're misreading that PEP. It does not say raise a class instead of an instance: both are fully supported.
Peter Hansen
+1  A: 

BTW You can throw any object

>>> for exc in "String Error", Exception("Real Exception"):
...     try:
...             raise exc
...     except Exception,e :
...             print "Caught:", e
...     except:
...             import traceback
...             traceback.print_exc()
...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
String Error
Caught: Real Exception
>>>
thanos
this possible only in py2.x
SilentGhost
This isn't even possible on all 2.xs. It will fail in 2.6 and above, after it was deprecated in 2.5. Raising a string is possibly the most horrible suggestion you could give here.
Devin Jeanpierre
Yes, -1, very bad idea.
Peter Hansen