Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function failed: Raise Exception, or return FALSE? What's the better approach?

Tags:

python

pep8

I was wondering how you guys handle functions fails. Do you raise an exception, or do you return an error message?

e.G. I have a function that is supposed to connect to an external com-object. If the com-object has not been initiated through another program, the connection cannot be established. What would be the preferred python way of notifying the main program? Should I raise an exception with the detailed error message, or should I simple return the error message?

Thanks!

like image 667
Muppet Avatar asked Feb 18 '12 18:02

Muppet


2 Answers

Throw an exception, this is what they are there for.

They allow the things using your code to manage the error, passing back strings provides too much opportunity for mishandling.

Consider the case you return a string or an iterable normally, checking for an error message could cause problems, and may not catch them all the time, it's also not very Pythonic.

like image 133
Gareth Latty Avatar answered Nov 10 '22 16:11

Gareth Latty


python absolutely comes down on the side of exceptions here. i have always found this article to be a great explanation.

like image 34
checkorbored Avatar answered Nov 10 '22 16:11

checkorbored