Elipsus
Elipsus

Reputation: 3

Why does this exception print as "list index out of range"?

I'm making a practice Wallet/money sending system, but for some reason, when commands[3] or commands[4] are out of range, it doesn't activate my if statement in the except statement. When I print e, it prints as "list index out of range".

Why does e print as "link index out of range", but when I run if e == "link index out of range" it returns False?

if command_keyword == "send":
        try:
            globals()[commands[2]].send_funds(globals()[commands[3]], int(commands[1]))
        except Exception as e:
            if e == 'list index out of range':
                print("'send' command requires three arguments. 'send [amount] [sender] [recipient]'")

Upvotes: 0

Views: 121

Answers (1)

Mia
Mia

Reputation: 2676

This is because the type of exception is IndexError and the information is an attribute of the exception. A better way to handle such exception is

if command_keyword == "send":
        try:
            globals()[commands[2]].send_funds(globals()[commands[3]], int(commands[1]))
        except IndexError:
            print("'send' command requires three arguments. 'send [amount] [sender] [recipient]'")

However, if you really want to check the message instead, you can retrieve it through e.args

if command_keyword == "send":
        try:
            globals()[commands[2]].send_funds(globals()[commands[3]], int(commands[1]))
        except Exception as e:
            if e.args[0] == 'list index out of range':
                print("'send' command requires three arguments. 'send [amount] [sender] [recipient]'")

However, note that this is not safe because not every exception has an argument and accessing e.args[0] may cause an IndexError itself.

Upvotes: 2

Related Questions