python - Except block not recovering from error -


in following code rpg, deal user input , therefore create code in way can handle errors. when user enters in game command such acquire (which takes 2 arguments) shown below, acquire function called, tries use second part of split input. if user enters 'acquire' , there no second part split string, expect indexerror raises , text printed. again, when code tries access rawinput[1] through items dictionary , fails find it, expect keyerror raised , text printed. none of happening me.

when each of these errors should raising, error i'm expecting occur occurs, try/ except block recover it.

items = { 'rapier': item('rapier', 1, [none, none], 2)}  def acquire(self):     try:         if pos[0] == self.pos[0] , pos[1] == self.pos[1]:             in range(1, 4):                 j = - 1                 if self.type == , not inventory[j]:                     inventory[j] = self                     self.pos = none                     print(name, 'picked the', self.name)                 elif none not in inventory:                     print(name, 'cannot carry more!')         else:             print('there no', rawinput[1].title(), 'here')     except keyerror:         print('that doesn\'t exist!')     except indexerror:         print('acquire takes 2 arguments')  def parseinput():     global rawinput     rawinput = input('> ').lower().split(' ', 1)      if rawinput[0] == 'acquire':         acquire(items[rawinput[1].title().strip()]) 

could explain me how fix code or explain happening?

the errors you're trying catch won't occur inside of code itself, rather when code interpreted. putting try-except around function call should fix it.

if rawinput[0] == 'acquire':     try:         acquire(items[rawinput[1].title().strip()])     except keyerror:         print('that doesn\'t exist!')     except indexerror:         print('acquire takes 2 arguments') 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -