Python 捕获“socket.error: [Errno 111] 连接被拒绝”异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14425401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:28:21  来源:igfitidea点击:

Catch "socket.error: [Errno 111] Connection refused" exception

pythonsockets

提问by URL87

How could I catch socket.error: [Errno 111] Connection refusedexception ?

我怎么能捕获socket.error: [Errno 111] Connection refused异常?

try:
    senderSocket.send("Hello")
except ?????:
    print "catch !"     

采纳答案by Martijn Pieters

By catching allsocket.errorexceptions, and re-raising it if the errnoattribute is not equal to 111. Or, better yet, use the errno.ECONNREFUSEDconstant instead:

通过捕获所有socket.error异常,并在errno属性不等于 111 时重新引发它。或者,更好的是,使用errno.ECONNREFUSED常量代替:

import errno
from socket import error as socket_error

try:
    senderSocket.send('Hello')
except socket_error as serr:
    if serr.errno != errno.ECONNREFUSED:
        # Not the error we are looking for, re-raise
        raise serr
    # connection refused
    # handle here