Python Forum

Full Version: What is the exception?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all! Here's some code:

from forex_python.converter import CurrencyRates
import datetime as dt
from time import sleep

def try_convert(country, date=''):
    success = False
    while success == False:
        try:
            res = c.get_rate('USD',country,date='')
        except:
            #Exception as e:
            #    print(e)
            #wait a while
            print('need to sleep')
            sleep(10)
    return res
First, did I handle Lines 5 and 9 correctly with regard to the 'date' argument?

Second, do Lines 11-12 make sense? I found a webpage stating that as a way to report a division-by-zero exception and thought it might work for all exceptions. It did not work here when I activated them (I don't understand them either because I've never seen a line in Python "X as y:" being short for "if X is y").
If you pass date as an arg you do not want to override the value. This code sets date = '' regardless of what value is passed when the method gets called.
res = c.get_rate('USD', country ,date='') # Overrides date argument.  Makes it always ''
Instead you simply want to do this:
res = c.get_rate('USD',country, date)
If the caller provides a date when calling the method, that value is passed to c.get_rate. If the caller doesn't provide a date then '' is used.
Note: you forgot to make an instance of CurrencyRates

Looking at the Github source
The get_rate method raises
RatesNotAvailableError
See
try:
    res = currency_rates.get_rate('USD', country, date)
except RatesNotAvailableError as error:
    print(f"Error raised: {error}"

You will be stuck in an infinite loop success is never altered from False
while success == False: