用异常处理替换if-else语句

时间:2015-06-18 20:15:46

标签: python exception-handling

我目前拥有下面的函数,其中包含if-else语句。阅读this post后,我认为最好使用try-catch异常处理。但是,我不知道该怎么做。基本上,如果输入的currency不是AUD,我想使用下面的print语句抛出异常。

def update(self, currency):
    if self.currency == 'AUD':
        url = 'http://www.rba.gov.au/statistics/tables/csv/f17-yields.csv'

        response = urllib2.urlopen(url)
        text = response.read()

        csvfile = StringIO.StringIO(text)
        df = pd.read_csv(csvfile)
        print df

    else:
        print('This currency is not available in Database')

3 个答案:

答案 0 :(得分:2)

您通常不想在同一个地方抚养和捕捉异常。相反,您希望引发首次发现错误的异常,并在报告问题的任何地方捕获它。

在您显示的代码中,您只想将print调用替换为raise语句,可能是ValueError。将您打印的文本作为参数传递给例外:

raise ValueError('This currency is not available in Database')

由于您还没有显示调用update的位置,因此我无法确定捕获异常的适当位置。异常有用的一个原因(而不是if / else测试)是你可以让异常从几个函数或结构块中冒出来,如果没有有用的方法来处理它们那个级别。

答案 1 :(得分:0)

使用异常处理而不是if-else语句会慢得多。

我已经对类似的比较进行了基准测试,以便在字典here中找到键列表,并附加时序。对我来说,它慢了5倍。

答案 2 :(得分:-1)

如果要强制进行异常处理,可以使用assert:

def update(self, currency):
    try:
        assert self.currency == 'AUD'
        url = 'http://www.rba.gov.au/statistics/tables/csv/f17-yields.csv'

        response = urllib2.urlopen(url)
        text = response.read()

        csvfile = StringIO.StringIO(text)
        df = pd.read_csv(csvfile)
        print df

    except AssertionError:
        print('This currency is not available in Database')

在这种情况下不一定是理想的(在我看来,这是一个LBYL场景),因为相等测试应该更快,更易读,并且对更多货币更好地扩展,假设你从广泛开始各种不同的货币。

相关问题