2016-11-27 15 views
0

次の関数を使用すると、with-statmentおよびa pop接続を使用できます。しかし、接続が確立されていない場合、quit()は最後に例外を発生させます。どのようにこれを修正することができますか?未接続の接続およびコンテンツマネージャー

@contextmanager 
def pop_connect(server, user, password, timeout, use_SSL=False): 
    try: 
     pop = poplib.POP3_SSL if use_SSL else poplib.POP3 
     pop_conn = pop(server, timeout=timeout) 
     pop_conn.pass_(password) 
     yield pop_conn 
    except poplib.error_proto as pop_error: 
     print('Authentication for receiving emails failed:{}'.format(pop_error)) 
    except OSError as os_error: 
     print('Name resolution or connection failed:{}'.format(os_error)) 
    finally: 
      pop_conn.quit() 

答えて

0

私はあなたがexceptアクションに対応するようpasstry:であなたのpop_conn.quit()を置くことができたとします

finally: 
    try: 
     pop_conn.quit() 
    except <WhaterverException>: 
     pass 
0

ソリューションは、ハンドラで例外を再スローすることです。コンテクストマネージャーは、収量を除いてはない:

@contextmanager 
def pop_connect(server, user, password, timeout, use_SSL=False): 
    try: 
     pop_conn = poplib.POP3_SSL(server,timeout=timeout) if use_SSL else poplib.POP3_SSL(server,timeout=timeout) 
     pop_conn.user(user) 
     pop_conn.pass_(password) 
     yield pop_conn 
    except poplib.error_proto as pop_error: 
     print('Receiving mail failed:{}'.format(pop_error)) 
     raise 
    except OSError as os_error: 
     print('Name resolution or connection failed:{}'.format(os_error)) 
     raise 
    finally: 
     try: 
      pop_conn.quit() 
     except UnboundLocalError: 
      pass 
関連する問題