Try/catch is to handle exceptions, not to handle return values from methods. In your case, what you wrote would compile but is not what you want to do.
The easiest solution for you would be it use what already exists in python, ie. socket, which can nicely validate IP for you. If you still want to use the validate() method for other purpose, then you can write:
import socket
def validate(a):
socket.inet_aton(s)
try:
validate(s)
# your code here
except socket.error:
print("insert your ip correctly")
In that case, the socket.inet_aton method will raise the exception socket.error
, which you can then catch. If for some reason you do not want to use socket, then you can define your own exception, raise it from validate() and catch it outside validate().
For Python 3, you will be better served by ipaddress as socket is too permissive (for good reasons, see man inet(3)):
import ipaddress
def validate(a):
ipaddress.ip_address(a)
try:
validate(s)
# your code here
except ValueError:
print("insert your ip correctly")
On a side note, I believe you want to return True
as the last line of validate(), but that would not change the problem.
On a (second) side note, catching all exceptions (bare catch
statement) is bad practice. In your code you handle a specific error (IP not valid) you should only catch exceptions related to this problem.