Chad Vernon
  • Home
  • Reel/Resume
  • Work
  • Resources
  • About
  • Contact
Home » Resources » Python Scripting for Maya Artists » Exceptions and Error Handling
sideBar

Search

Categories

  • CG
  • cvxporter
  • Maya
  • Personal

Archives

  • July 2010
  • May 2010
  • April 2010
  • March 2010
  • December 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • September 2008
  • August 2008
  • July 2008
  • June 2008
  • May 2008
  • April 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007

Rss

  • Main Entries RSS
  • Comments RSS

Exceptions and Error Handling

Whenever an error is encountered in your program, Python will raise an exception stating the line number and what went wrong:

>>> x = [1,2,3]
>>> x[10]
Traceback (most recent call last):
File "
", line 1, in
x[10]
IndexError: list index out of range

If we want the code to continue running, we can use a try/except block:

>>> x = [1,2,3]
>>> try:
>>>     x[10]
>>> except IndexError:
>>>     print "What are you trying to pull?"
>>> print "Continuing program..."

Another variation is:

>>> x = [1,2,3]
>>> try:
>>>     x[10]
>>> except IndexError:
>>>     print "What are you trying to pull?"
>>> else:                   # Will only run if no exception was raised
>>>     print "No exception was encountered"
>>> print "Continuing program..."

You can raise your own exception if you want to prevent the script from running:

>>> if func() == "bad return value":
>>>     raise RuntimeError("Something bad happened")
Home » Resources » Python Scripting for Maya Artists » Exceptions and Error Handling

© 2010 Chad Vernon