2013-05-08 100 views
1

我在Python中有一个类函数,可以返回成功或失败,但如果发生故障,我希望它发回特定的错误字符串。我心里有3种方法:从Python中的函数返回错误字符串

  1. 传递一个变量ERROR_MSG到最初设置为无,在一个错误的情况下,它被设置为错误字符串的函数。例如:

    if !(foo(self, input, error_msg)): 
        print "no error" 
    else: 
        print error_msg 
    
  2. 返回包含函数的bool和error_msg的元组。

  3. 我在发生错误时引发异常并在调用代码中捕获它。但是由于我没有看到我正在使用的代码库中经常使用异常,所以不太确定采用这种方法。

什么是Pythonic这样做?

+2

为什么不例外? – 2013-05-08 22:50:57

回答

8

创建自己的异常,并提高该相反:

class MyValidationError(Exception): 
    pass 

def my_function(): 
    if not foo(): 
     raise MyValidationError("Error message") 
    return 4 

然后,您可以调用你的函数为:

try: 
    result = my_function() 
except MyValidationError as exception: 
    # handle exception here and get error message 
    print exception.message 

这种风格被称为EAFP(“易请求原谅比许可” )这意味着你写的代码是正常的,出现异常时会引发异常,并在稍后处理:

This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

5

引发错误:

if foo(self, input, error_msg): 
    raise SomethingError("You broke it") 

而且处理:

try: 
    something() 
except SomethingError as e: 
    print str(e) 

这是Python的方法和最可读的。

返回像(12, None)这样的元组可能看起来是一个很好的解决方案,但如果不一致,很难跟踪每种方法的返回结果。返回两种不同的数据类型更糟糕,因为它可能会破坏假定数据类型不变的代码。