from tornado import gen from tornado.ioloop import IOLoop @gen.coroutine def throw(a,b): try: a/b raise gen.Return(‘hello‘) except Exception, e: pass @gen.coroutine def test(): print "i‘m ok" res = yield throw(1,1) print res #res始终为None print "here too" test() IOLoop.instance().start()
res = yield throw(1,1)这里res获取的结果始终为空,因为throw内部用了try...except...,而@gen.coroutine本身就是以抛出异常的形式返回的,所以不管throw函数里的a/b这一句有不有异常,不管调用throw(1,0)还是throw(1,1)返回的都是None,
正确的做法是在外部调用的位置添加try...catch... 即:
@gen.coroutine def throw(a,b): a/b raise gen.Return(‘hello‘)
@gen.coroutine def test(): print "i‘m ok" try: res = yield throw(1,0) except Exception, e: print ‘EXCEPTION!‘, e print "here too" test() IOLoop.instance().start()
参考:https://github.com/tornadoweb/tornado/issues/759
如何捕捉@tornado.gen.coroutine里的异常
原文:http://www.cnblogs.com/ymy124/p/5053432.html