【问题标题】:python try except in socket not workingpython尝试除了套接字不起作用
【发布时间】:2018-02-11 17:59:06
【问题描述】:

我的代码是:

usso = socket.gethostbyname("site.com")
try:
    usso
except socket.gaierror:
    uss = 0
else:
    uss = 1
if uss == 1:
    print ("Site Is True")
elif uss == 0:
    print ("Site Is Wrong")

但除了不工作,结果是:

Traceback (most recent call last):
  File "test.py", line 22, in <module>
    usso = socket.gethostbyname("site.com")
socket.gaierror: [Errno -2] Name or service not known

有什么问题?

【问题讨论】:

    标签: python sockets try-catch except


    【解决方案1】:

    您必须将可能导致异常的语句放入 try catch 块中。在原始代码中,异常发生在 try catch 块之前,即第一行。

    试试这个

    try:
        usso = socket.gethostbyname("site.com")
    except socket.gaierror:
        uss = 0
    

    【讨论】:

      【解决方案2】:

      您的代码未包含在“try”块中。 应该是:

      try:
          usso = socket.gethostbyname("site.com")
      except socket.gaierror:
          print 'yolos'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-29
        • 1970-01-01
        • 1970-01-01
        • 2014-02-19
        • 1970-01-01
        • 2021-01-07
        • 1970-01-01
        • 2018-07-20
        相关资源
        最近更新 更多