-1

i have a code :

s = '127.0.0.0'

def validate(a):
    a = s.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return False

try:
    validate(s) #ip validation
    #my code here
except :
    print("insert you're ip correctly")

can i combine if else with try catch like that?

if the try catch got error message or like return false from if condition it will run the except condition, if not it will run the try condition until the process is end.

there's have a better ways to dot this?

Taku
  • 31,927
  • 11
  • 74
  • 85
Nedy Suprianto
  • 201
  • 1
  • 6
  • 14
  • 1
    You are not `raise`ing an exception, either `raise` in `validate()` or `assert validate(s) == True` (Note: you never `return True` from `validate()`) – AChampion Jun 06 '17 at 05:26
  • more ways to do https://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python – JkShaw Jun 06 '17 at 05:29

3 Answers3

1

You can raise an exception if the function returns False, by doing:

s = '127.0.0.0'

def validate(a):
    a = a.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return True

try:
    if not validate(s): #ip validation
        raise TypeError
except TypeError:
    print("insert you're ip correctly")

Note: you probably want to return True for the end, since I believe that's when the function validates successfully, and a = a.split('.') not s.split, or else you're splitting the global variable s.

Tip: when using try...except, try to catch a specific error than to use the catch-all except:.

Taku
  • 31,927
  • 11
  • 74
  • 85
1

The answers above may be technically correct, but considering coding style etc. I don't see any reason to use exceptions here instead a plain if else:

if not validate(s): #ip validation
    print("insert you're ip correctly")

That actually does what you want and it's much cleaner and better to read.

sebastian
  • 9,526
  • 26
  • 54
0

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.

Guillaume
  • 2,325
  • 2
  • 22
  • 40
  • i already try with socket, but i think there's still have a problem, when i input the ip with 1.1.1 the **socket** still recognize that's a IP, whereas a IP have 4 octets not 3 octets i use validate() function to make it more specific. – Nedy Suprianto Jun 06 '17 at 06:30
  • Fair enough. I added an option for python 3 which would fit your needs better. – Guillaume Jun 06 '17 at 06:46