Try / except not working with a specific exception in Python

291 views Asked by At

I'm trying to solve a specific error from a library (pycountry_convert) in a code with try / except, but when I use the except to avoid this case it just doesn't work. I've tried so many things to solve this.

Here is the code

import pycountry_convert as pc

def pegacontinente(nomepais):
    
  

    
    nomepais = nomepais.replace("-", " ")

   
    e = ['and', 'the']
    nomepais = ' '.join([word.capitalize() if word not in e else word for word in nomepais.split()])

    
    country_code = pc.country_name_to_country_alpha2(nomepais, cn_name_format="default")
 
    try:
        continent_name = pc.country_alpha2_to_continent_code(country_code)

    except Exception as e:
        # Special Case: Timor Leste
        if e == "Invalid Country Alpha-2 code: \'TL\'":
            continent_name = 'AS'
        else:
            continent_name = 'N/A'
        
    return continent_name

In the case of Timor Leste, this code returns "N/A", when it's suppose to return 'AS'. I already tried to use "" before quote marks, remove all special characters from the string but it just don't work and I'm getting very frustrated.

I tried to do something like the image below to see if there is any typo at my string or something but it works out of the try/except thing

enter image description here enter image description here

2

There are 2 answers

2
Yuri Reis Valete On

I just found the answer even though I didn't understand it. The solution for my problem found here .

I don't know why but when I use repr(e) == "KeyError(\"Invalid Country Alpha-2 code: \'TL\'\")" instead of e == "\"Invalid Country Alpha-2 code: \'TL\'\"" it works. If any person could explain me why so I can't think that python just hates me I would be greatful.

Thanks for @mace and @ThomasWeller that tried to help me :)

0
Mace On

I have looked into your problem and it's kind of tricky because of extra quotes "" that are being added to the exception-string.

I have condensed your code to the problem part and print 3 different ways to look at exception e.

import pycountry_convert as pc

country_code = 'TL'

print("                                                  hello")

try:
    continent_name = pc.country_alpha2_to_continent_code(country_code)
except Exception as e:

    print(f'type e -       {type(e)}       value    {e}')
    print(f'type str(e) -  {type(str(e))}            value    {str(e)}')
    print(f'type repr(e) - {type(repr(e))}            value    {repr(e)}')

    if e == '"Invalid Country Alpha-2 code: \'TL\'"':
        print("TRUE 1")
    else:
        print("FALSE 1")

    if str(e) == '"Invalid Country Alpha-2 code: \'TL\'"':
        print("TRUE 2")
    else:
        print("FALSE 2")

    if repr(e) == "KeyError(\"Invalid Country Alpha-2 code: \'TL\'\")":
        print("TRUE 3")
    else:
        print("FALSE 3")

This is the output:

                                                  hello
type e -       <class 'KeyError'>       value    "Invalid Country Alpha-2 code: 'TL'"
type str(e) -  <class 'str'>            value    "Invalid Country Alpha-2 code: 'TL'"
type repr(e) - <class 'str'>            value    KeyError("Invalid Country Alpha-2 code: 'TL'")
FALSE 1
TRUE 2
TRUE 3

The first thing you can see is that "hello" prints without the quotes but the e-values print with quotes. So arround the e-messages/strings there are extra "". In your first code they were missing ("Invalid ... \'TL\'") but in your answer code they are placed arround the string ("\"Invalid ... \'TL\'\"").

What you can also see in my example output is that e is of type 'KeyError'.

You can't compare type 'KeyError' with type string. So you have to cast/change e to a string with str(e) before comparing.

You can also use repr(e) wich also 'converts' e to a string. But this adds the extra "KeyError(..." to the string.

The solution closest to your initial code would be

# Special Case: Timor Leste
if str(e) == '"Invalid Country Alpha-2 code: \'TL\'"':

which changes e into a string and adds extra quotes "" arround your initial string.