Guarding arithmetic

Laszlo Nagy gandalf at shopzeus.com
Thu Aug 23 05:23:20 EDT 2012


On 2012-08-23 11:05, Mark Carter wrote:
> Suppose I want to define a function "safe", which returns the argument passed if there is no error, and 42 if there is one. So the setup is something like:
>
> def safe(x):
>     # WHAT WOULD DEFINE HERE?
>
> print safe(666) # prints 666
> print safe(1/0) # prints 42
>
> I don't see how such a function could be defined. Is it possible?
You are very vague. "There is an error" - but what kind of error? To 
catch all possible exceptions you could do:

def unsafe(x):
     # put your code here...

def safe(x):
     try:
         return unsafe(x)
     except:
         return 42

Generally, it is a bad idea. Exception handlers were invented because 
they give you a way to handle any error in the call chain. When an 
exception occurs, the interpreter will start searching for an 
appropriate exception handler traversing up in the call chain. By 
converting exceptions into return values, you are bypassing this search. 
Then you will have to write conditions instead of exception handlers 
inside ALL methods in the call chain, creating a "manual" search for the 
handler of the exception. In most cases, this will make your code 
difficult, error prone and hard to read.

In some special cases, this can be a good idea to do.

Can you please let us know when and how would you like to use it?





More information about the Python-list mailing list