Page 1 of 1

Invoking a custom exception in Python

Posted: Mon Jan 21, 2008 10:39 pm
by evilmonkey
Hi All,

Can someone please point me in the right direction with regards to invoking a custom exception in python? For example, if I try to pop an stack that doesn't have any values, python throws an exception called IndexError. What if I want it to invoke MyError (which is a programmer-defined subclass of Exception)? This is driving me up the wall and the python manual is no help. :banghead: Help is appreciated.

Re: Invoking a custom exception in Python

Posted: Sat Jan 26, 2008 12:37 am
by Chris Corbyn
Do you mean you want python to throw a different type of error to what it was going to throw? Or do you just mean you want to be able to throw exceptions from your own code? I doubt you can change the types of exceptions python throws itself since that would go against the nature of exceptions.

A quick Google search shows this:

Code: Select all

raise YourError, 'Your Message'
You could catch python's error and raise your own too if my educated guesswork proves me right.

Code: Select all

try:  #some python code hereexcept IndexError:  raise YourError