2

I am trying to run multiple functions in a try/except but not sure if this is the correct way. Should I have an except for each possible errors for each function returns?

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
Doritos
  • 403
  • 3
  • 16
  • 2
    you will not reach to `return sock`. – vb_rises May 07 '19 at 13:21
  • 1
    Don't use blanket `except:` clauses unless you re-raise the exception. This isn't Pokemon, you do not want to catch them all, you don't want to catch memory errors or keyboard interrupts or generator exit signals. The *first* exception will be caught, the remainder of the block is not executed. If that's the goal, then this is fine, just *limit what you catch*. – Martijn Pieters May 07 '19 at 13:24
  • Yes. Try to aim for atomicity – Vic May 07 '19 at 13:36

1 Answers1

2

Basically it's a compromise between code-style, readability and length of code.

The best practice calls for minimal try clauses as possible, however if several function calls raise the same exceptions you may group them together.

However a naked except clauses are almost never considered a good practice (see Should I always specify an exception type in `except` statements? for example).

I'd refactor the above example to:

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

Although it may make more sense to re-raise the exception to the calling code to catch rather than returning an implicit 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
DeepSpace
  • 78,697
  • 11
  • 109
  • 154