我学习了如何添加错误处理。但是对于何时需要将其添加到我的代码中,我有点困惑。
请参见以下示例。
我是否需要对调用套接字的每一行进行错误处理?
Server.py
import socket
sockfd = socket.socket()
try:
sockfd.bind(("127.0.0.1", 20001))
except socket.error as emsg:
print("Socket bind error: ", emsg)
sys.exit(1)
print("I_am", socket.gethostname(), "and_I_am_listening_...")
sockfd.listen(5)
new, who = sockfd.accept() # Return the TCP connection
print("A_connection_with", who, "has_been_established")
try:
message = new.recv(50)
except socket.error as err:
print("Recv error: ", err)
if message:
print("\'"+message.decode("ascii")+"\'", "is received from", who)
else:
print("Connection is broken")
new.close()
sockfd.close()
最佳答案
一种常见的错误处理方法是在有可能发生意外情况时添加该错误,即编写代码时您没想到的事情。这意味着如果您有一个简单的函数,您知道其可能的不同错误状态,即无需添加尝试语句,因为您可以使用以下方法处理错误: if-else语句。由于try块具有更大的开销,因此通常还可以减少内存消耗。但是,如果您不知道或无法控制某些事情,例如外部程序返回或API调用,即应添加错误处理的时间。
关于python - 我们什么时候在程序中添加错误处理代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66260158/