class InvalidAnimalError(Exception):
pass
class Animal:
def make_sound(self):
raise NotImplementedError
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
class Bird(Animal):
def make_sound(self):
return "Tweet!"
class SoundMaker:
def play_sound(self, animal):
if animal is None:
raise InvalidAnimalError("Animal cannot be None")
if isinstance(animal, Dog):
return animal.make_sound()
elif isinstance(animal, Cat):
return animal.make_sound()
elif isinstance(animal, Bird):
return animal.make_sound()
else:
raise ValueError("Unsupported animal type")
# 测试代码
sound_maker = SoundMaker()
dog = Dog()
cat = Cat()
bird = Bird()
try:
print(sound_maker.play_sound(dog))
print(sound_maker.play_sound(cat))
print(sound_maker.play_sound(bird))
print(sound_maker.play_sound(None))
except InvalidAnimalError as e:
print(f"Error: {e}")
except ValueError as e:
print(f"Error: {e}")