Reputation: 71
Hi I have started coding in python lately and I am wondering how to handle errors. I did the tutorial diveintopython and there he uses raise error to give feedback whats going wrong. Here my case: I have a function which checks if a string, representing a number, is 7 or 8 digits long and some other things
def checkNumber( someNumber ):
''' checks if Number is valid '''
someNumber = str(someNumber);
if not 6 < len(someNumber) < 9:
raise ValueError('number must be either 7 or 8')
if not re.search('^[0-9]{7,8}$', someNumber):
raise ValueError('only digits from 0...9')
sum = 0
if len(pzn) == 7: someNumber = '0' + someNumber
for n, a in list(enumerate(someNumber[:-1], start=1)):
sum += int(a)*n
if someNumber[-1]==str(sum%11):
return someNumber
else:
raise ValueError('not a vaild code')
I am using this function standalone, but I will also call it from an other function, which scans barcodes and calls this function to validate the code. So if the scan number is correct it should go on and if not it should continue scanning. Is it better to do it like i did and put a try/except block in the scanner function or should I return a False
Thanks a lot
Upvotes: 2
Views: 9263
Reputation: 6661
Purists will say that in Python "it is Easier to ask forgiveness than permission", which means, you should always use exceptions whenever possible.
I also prefer to use exceptions, when it makes sense. For a method which intuitively should return True
or False
(for example something like is_valid_number()
), I simply find more obvious/readable to just return the boolean value and not raise any exception.
Now for a method like convert_number()
, you want use exceptions otherwise the handling of return codes will probably turn your code into a mess.
From your code, I find you should not do return someNumber
at the end; you could simply return True
or False
.
If you are interested in why the check failed, then using exceptions is the way to go because you can cleanly return an "error message" to the caller. In this case you also do not need to return anything, the fact that you call it and it doesn't raise any exceptions already means the number is valid.
Finally, if your intention is to convert the number into something else, well, then your method should be called convert_number()
, return the number if everything is ok, and raise an exception in case of error.
Upvotes: 3
Reputation: 1124388
It's better to raise an exception, that's what exceptions are for.
Also, returning False
would require your code to handle testing the difference between 0
and False
. Suddenly you need to test the return value of your function.
Your function does seem to suffer from a split personality. On the one hand you named it checkNumber
, and your documentation claims it is checking if the number is valid. On the other hand it is transforming, altering that number, converting it to a string, and even prepending a 0
to it if the pzn
global has a length of 7.
If all your function does is testing if the number is valid, then returning a boolean makes sense. Using exceptions can then give you more information on the nature of the validation failure perhaps, but a boolean could be enough if you do not need that information.
But if you also need to transform your number to a different type and format, you need to rename your function, and make then a validation error is really an exception to the normal behaviour. The expectation is then that the function returns a transformed value, and invalid input should raise an exception to indicate that it could not return a normal value because of some error in the input.
Upvotes: 9