Tuesday, March 17, 2009

Mimicking Exceptions in Fibra

When a fibra schedule is running, a task can yield a sub task and pause until the sub task completes and returns a value to the parent task.

This works well, however, when an exception occurs in the sub task, the parent task does not receive the exception. This is a real pain, and breaks my normal thinking about exception handling. When using normal function calls, the exception should always bubble up the stack until it is handled. Fibra should provide the same behavior for sub tasks.

Well, now it does. Snippet below.

import fibra

def sub_task(x):
if x < 5:
yield fibra.Return(x**x)
else:
raise ValueError("x must be < 5")

def main_task():
# launch a sub task
# wait for it to finish and collect the result.
x = yield sub_task(4)
print x
# the sub task will raise an exception here...
# yet the exception will bubble up to the parent task,
# just like a regular function call.
try:
x = yield sub_task(5)
except ValueError:
print "Oops, an exception occured."

schedule = fibra.schedule()
schedule.debug = True
schedule.install(main_task())
schedule.run()

>>> 256
>>> Oops, an exception occured.

These features will arrive with Fibra 0.0.11, which is coming Real Soon Now.

2 comments:

Michael said...

Very nice :-)

Anonymous said...

small offtop,
is there any documentation or tutorial with fibra or i have to look throught code and read examples in this blog?

Popular Posts