From BlenderWiki

Jump to: navigation, search

An important part of writing computer programs - which is what our scripts are - is anticipating and handling what can go wrong. A traditional method of dealing with errors is to return an error status or code after each method or function we call. This looks something like this:

error = do_something()
if error:
 # code to handle the error
 # ...
 
error = do_something_else()
if error: 
 # code to handle this error
 # ...

Not very pretty, is it? It is also hard to extend when creating functions. Python has a nice feature called 'Exceptions' for dealing with errors. Essentially, you try to do something and if it works, everything is fine. If not, an object called an Exception is created. Normally, you create a block of code to handle the exception. If you don't, the Python interpreter stops and prints the text representation of the exception.

The syntax for exception handling looks like this:

try:
  do_something()
  do_something_else()
except:
  # handle any problems here
  # ...

A real example will make this clearer. First, let us try getting an non-existent object by name. Using our default scene with a Cube, enter and run the code below in a Text window:

import Blender as B
 
B.Object.Get('non-existent-object')

In our output window we see something like this:

Traceback (most recent call last):
  File "Text.002", line 3, in ?
ValueError: object "non-existent-object" not found

When Object.Get() is called with a name like 'non-existent-object', it creates or 'throws' a ValueError exception. Since there is no code to handle the exception object, the interpreter prints it out and stops. Not exactly nice behavior! Here is the syntax we use to process the exception ourselves:

try:
  B.Object.Get('non-existent-object')
except ValueError:
  print 'Sorry. Object not found!'

The code in the try block is executed. If our object is found, the exception block is ignored. If a ValueError is thrown, then the exception block is executed.

You can read more about Python exceptions here: http://docs.python.org/tut/node10.html

Note that you can have multiple except clauses, each with a different exception or, for the last one, a default.