Make Your Own Python Text Adventure by Phillip Johnson

Make Your Own Python Text Adventure by Phillip Johnson

Author:Phillip Johnson
Language: eng
Format: epub
Publisher: Apress, Berkeley, CA


Raising Exceptions Intentionally

It may seem counter-intuitive at first, but there are some scenarios where we actually want to cause an exception to be raised. We usually do this when we want to yell at ourselves for doing something wrong! Putting in checks for bad code will help us catch errors during testing.

One vulnerability in the current code is with the Weapon class . This code would cause an exception:

1 axe = Weapon()

2 print(axe)

Why? Because the __str__() method of the Weapon class looks for a name when printing the object, but the class doesn’t have that attribute. We could fix this by assigning a name to Weapon, but that doesn’t really make sense because the class is too general to describe. Really, we should never create a Weapon object; we should always create a specific subclass like Dagger. If we need an axe object, we should create an Axe class that inherits from the superclass Weapon.

To prevent ourselves from accidentally creating Weapon objects, we can raise an exception in the initializer.

1 class Weapon:

2 def __init__(self):

3 raise NotImplementedError("Do not create raw Weapon objects.")

4

5 def __str__(self):

6 return self.name



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.