python try except in socket not working

1.6k Views Asked by At

My Code is:

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")

but except not working and result is:

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

What is the Problem?

2

There are 2 best solutions below

0
On

You have to put the statements that can cause exception into try catch block. In the original code the the exception occurred before the try catch block i.e. on first line.

Try this

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

Your code not include in "try" block. It should be:

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