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