尝试多种功能,除了

时间:2019-05-07 13:19:13

标签: python-3.x

我试图在try / except中运行多个功能,但不确定这是否正确。对于每个函数返回的每个可能的错误,我是否应该有一个例外?

def connect_to_server(ip, port):
    try:
        sock = networking.create_socket()
        sock.connect((ip, port))
        _thread.start_new_thread(recv_data, (sock, ))
        print("Connected to on port [" + str(port) + "]")
    except:
        print("Unable to connect to engine.")
        return

    return sock

1 个答案:

答案 0 :(得分:2)

基本上,这是代码风格,可读性和代码长度之间的折衷。

最佳实践要求尽可能少的try子句,但是,如果多个函数调用引发相同的异常,则可以将它们分组在一起。

但是几乎从来没有将裸露的except子句视为好习惯(例如,参见Should I always specify an exception type in `except` statements?)。

我将上述示例重构为:

def connect_to_server(ip, port):
    try:
        sock = networking.create_socket()
        sock.connect((ip, port))
    except SocketError:  # or whatever exception type you expect
        print("Unable to connect to engine.")
    else:
        _thread.start_new_thread(recv_data, (sock, ))
        print("Connected to on port [" + str(port) + "]")
        return sock

尽管重新引发调用代码中的异常以捕获而不是返回隐式None可能更有意义:

def connect_to_server(ip, port):
    try:
        sock = networking.create_socket()
        sock.connect((ip, port))
    except SocketError:  # or whatever exception type you expect
        print("Unable to connect to engine.")
        raise
    else:
        _thread.start_new_thread(recv_data, (sock, ))
        print("Connected to on port [" + str(port) + "]")
        return sock