Jojo
Jojo

Reputation: 1117

Replacing if-else statement with Exception Handling

I currently have the function below which has an if-else statement within it. After reading this post I thought it may be better to use try-catch Exception Handling instead. However, I am not sure how to do this. Basically, if the currency inputted is not AUD I want to throw an Exception with the print statement below.

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')

Upvotes: 0

Views: 844

Answers (3)

Blckknght
Blckknght

Reputation: 104722

You generally don't want to be raising and catching an exception at the same place. Instead, you want to raise the exception where the error is first noticed, and catch it wherever it makes sense to report the issue.

In the code you've shown, you just want to replace the print call with a raise statement, probably of a ValueError. Pass the text you're printing as an argument to the exception:

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

Since you haven't shown where update is called, I don't know for sure where it would be appropriate to catch the exception. One reason that exceptions are useful (rather than if/else tests) is that you can let the exception bubble out of several functions or structural blocks if there's no useful way to handle them at that level.

Upvotes: 2

Alex Huszagh
Alex Huszagh

Reputation: 14614

If you want to force exception handling, you can use 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')

Not necessarily ideal in this case (this is a LBYL scenario, in my opinion), since the equality test should be faster, more readable, and scale better to more currencies, assuming you start off with a wide variety of different currencies.

Upvotes: -1

StackG
StackG

Reputation: 2858

Using exception handling instead of an if-else statement will be much slower.

I've benchmarked a similar comparison for locating a list of keys in a dictionary here, and timings are attached. For me, it was 5 times slower.

Upvotes: 0

Related Questions