Invoking a custom exception in Python

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Invoking a custom exception in Python

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Invoking a custom exception in Python

Post 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
Post Reply