Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python尝试,但套接字不工作_Python_Sockets_Try Catch_Except - Fatal编程技术网

python尝试,但套接字不工作

python尝试,但套接字不工作,python,sockets,try-catch,except,Python,Sockets,Try Catch,Except,我的代码是: 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): F

我的代码是:

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
回溯(最近一次呼叫最后一次):
文件“test.py”,第22行,在
usso=socket.gethostbyname(“site.com”)
socket.gaierror:[Errno-2]名称或服务未知

问题是什么?

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

试试这个

try:
    usso = socket.gethostbyname("site.com")
except socket.gaierror:
    uss = 0
您的代码未包含在“try”块中。 应该是:

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