Is it better to use exception or return code in Python?

You may know this recommendation from Microsoft about using exceptions in .NET:

Performance rating

...

Throw exceptions only for emergency conditions, ...

Also, do not throw an exception when the return code is sufficient ...

(see all text http://msdn.microsoft.com/en-us/library/system.exception.aspx .)

As a comparison point, would you recommend the same for Python code?

+37
performance python exception
Jul 20 '09 at 9:18
source share
6 answers

Pythons need to be done to raise and handle exceptions. The excellent Python book in a nutshell discusses this in Error Checking Strategies in Chapter 6.

The book discusses EAFP ("easier to apologize than permission") compared to LBYL ("look before you jump").

So, to answer your question:

No, I would not recommend the same for python code. I suggest you read Chapter 6 of Python in a nutshell .

+33
Jul 20 '09 at 9:21
source share

The best way to understand the exceptions is " if your method cannot do what its name says, give it up ." My personal opinion is that this tip should apply the same for both .NET and Python.

The main difference is that you have methods that often cannot do what their name says, what they should do, for example, parse strings as integers or retrieve a record from the database. C #'s style is to avoid an exception in the first place:

int i; if (Int32.TryParse(myString, out i)) { doWhatever(i); } else { doWhatever(0); } 

while Python is much more convenient in this:

 try: i = int(myString) except ValueError: i = 0 doWhatever(i); 
+9
Jul 20 '09 at 12:02
source share

In exceptions, Python is not as expensive as in some other languages, so I would not recommend avoiding exceptions. But if you make an exception, you usually want to catch it somewhere in your code, there will be an exception if a fatal error occurs.

+8
20 '09 at 9:23
source share

Python is usually focused on expressiveness.
I would apply the same principle here: usually you expect a function to return a result (according to his name!), not an error code.
For this reason, it is usually better to throw an exception than return an error code.

However, what is stated in the MSDN article also applies to Python, and it really is not related to returning an error code instead of an exception.
In many cases, you can see the exception handling used for normal flow control and for handling expected situations. In certain environments, this has a huge impact on performance; in all environments, it has a great influence on the expressiveness and maintainability of the program.

Exceptions for exceptions that are outside the normal flow of the program; if you expect something to happen, then you should contact directly and then pick up everything that you cannot expect / process.

Of course, this is not a recipe, but only a heuristic; the final decision always depends on the developer and the context and cannot be specified in a fixed set of manuals - and this is much more true for exception handling.

+7
Jul 20 '09 at 11:49
source share

I did a simple experiment to compare exception collection performance with the following code:

 from functools import wraps from time import time import logging def timed(foo): @wraps(foo) def bar(*a, **kw): s = time() foo(*a, **kw) e = time() print '%f sec' % (e - s) return bar class SomeException(Exception): pass def somefunc(_raise=False): if _raise: raise SomeException() else: return @timed def test1(_reps): for i in xrange(_reps): try: somefunc(True) except SomeException: pass @timed def test2(_reps): for i in xrange(_reps): somefunc(False) def main(): test1(1000000) test2(1000000) pass if __name__ == '__main__': main() 

With the following results:

  • Exception exceptions: 3.142000 sec
  • Using return : 0.383000 sec

Exceptions are about 8 times slower than using return .

+5
Jun 28 '13 at 7:55
source share

I think that returning an error code or throwing an exception is something very valid that you might think about, and cross-linguistic comparison can be useful and informative. I think that a very generalized answer to this concern is just a consideration: the set of valid return values โ€‹โ€‹for any function should be made as small as possible and as necessary .

As a rule, this will mean that if this method returns an integer in one test case, users can rightfully expect that the method always returns an integer number or throws an exception. But, of course, a conceptually simple way is not always the best way to handle things.

The return value of the smallest surprise is usually None ; and if you look at it, you will see that its semantics is None , which licenses its use in all directions: it is a singleton immutable value, which in many cases evaluates to False or prohibits further calculations - not concatenation, without arithmetic. Therefore, if you decide to write a frob(x) method that returns a number for string input, and None for non-numeric strings and any other input, and you use this inside an expression like a=42+frob('foo') , you still you get the exception very close to the point at which the fictitious action occurred. Of course, if you type frob('foo') into a database column that was not defined using NOT NULL , you may run into problems, possibly in a few months. This may or may not be justified.

Therefore, in most cases, when you, for example, want to print a number from a string using something like bare float(x) or int(x) , this is the way to go, since these built-in modules will throw an exception if averaged data is not specified. If this is not suitable for your use, consider returning None from the user method; basically, this return value tells consumers that "Sorry, I could not understand your contribution. But you only want to do this if you positively know that your program makes sense from this point of view onwards.

You see, I just found out how to turn every notification, warning, and error message into a potential show-stopping exception in, m, PHP. It just drives me crazy that a typo in the variable name is generated in the standard PHP configuration, nothing but notification to the user . This is therefore bad. The program simply continues to do something with program code that does not make sense at all! I canโ€™t believe that people find this feature.

In the same way, it should be considered as follows: if at any moment of time it is possible to assert with sufficient justification that the execution of a part of the code no longer makes sense - since there are no values, they come from either an unexpected type, or when resources such as connecting to the database have decreased - It is extremely important to minimize debugging headaches, disrupt execution and manual control to any level in the code that has the right to handle failure.

Experience has shown that abstaining from early action and the ability to push dummy values โ€‹โ€‹to your data is useless, except that your code is more difficult to debug. So many examples of overly hard casting: allows you to add integers to floating elements. So that a string containing only digits added to a number is a fictitious practice that can create strange, non-localized errors that can occur on any given string that processes this data.

+3
Aug 13 '09 at 0:03
source share



All Articles