zoukankan      html  css  js  c++  java
  • 如何捕捉@tornado.gen.coroutine里的异常

    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

  • 相关阅读:
    第八周上机
    第七周作业
    第七周上机练习
    第六周作业
    第六次上机
    第五次上机
    第四周作业
    第四周上机练习
    第三次作业
    第二次作业
  • 原文地址:https://www.cnblogs.com/ymy124/p/5053432.html
Copyright © 2011-2022 走看看