Notes on Exception Handling in Python

本文介绍了Python中常见的异常类型,如IOError、ImportError等,并通过示例展示了如何使用try-except语句来处理这些异常。此外,还讲解了finally、else等关键字在异常处理中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Note: error and exception are the same in Python.

Common Exception

  • Exception Almost all the others are built off of it.
  • AttributeError Raised when an attribute reference or assignment fails.
  • IOError Raised when an I/O operation (e.g. a print statement, the built-in open() functio or a method of a file object) fails for an I/O-related reason, e.g. “file not found” or “disk full”.
  • ImportError Raised when an import statement fails to find the module definition or when a from ... import fails to find a name that is to be imported.
  • IndexError Raised when a sequence subscript is out of range.
  • KeyError Raise when a mapping (dictionary) key is not found in the set of existing keys.
  • KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+c or Del).
  • NameError Raised when a local/global name is not found.
  • OSError Raised when a function returns a system related error.
  • SyntaxError Raised when the parser encounters a syntax error.
  • TypeError Raised when an operation or function is applied to an object of inappropriate type. The associated value is string details about the type mismatch.
  • ValueError Raise when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
  • ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.

How to handle Exceptions

try:
    1/0
except ZeroDivisionError:
    print('You cannot divide by zero.')

# KeyError
my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
    value = my_dict['d']
exception KeyError:
    print('That key does not exist!')

# IndexError
my_list = [1, 2, 3]
try:
    my_list[5]
except IndexError:
    print('Index out of range.')

# A standard way to catch multiple exceptions
my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
    value = my_dict['d']
except IndexError:
    #pass
except KeyError:
    #pass
except KeyError:
    #pass
except:
    #pass

Bare Excepts

# This is NOT recommended!
try:
    1/0
except:
    print('...')

The finally Statement

You can use the finally statement to clean up after yourself. You would also put the exit code at the end of the finally statement.

my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
    value = my_dict['d']
except KeyError:
    # pass
finally:
    # pass

try/except, or else

The else will only run if there are no errors raised.

my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
    value = my_dict['d']
except KeyError:
    # pass
else:
    print('NO error occurred!')
finally:
    print('....')

The only good usage of else statement is where you want ot execute a second piece of code that can also raise an error. Of course, if an error is raised in the else, it won’t get caught.

<think>好的,我现在需要帮助用户按照给定的Python概念和项目结构来修改他们的代码。用户列出的Python概念包括面向对象编程、迭代器、JSON文件存储、异常处理和随机化。项目结构包含多个模块文件,如main.py、player.py等。首先,我需要逐一分析每个概念如何整合到对应的模块中。 首先看面向对象编程部分。用户需要设计多个类,如Player、Dungeon、Room、Item、Enemy,并使用继承和多态。例如,Enemy可能有不同的子类,每个有不同的攻击方式。我需要确保这些类之间有适当的继承关系,并利用多态方法,比如不同的Enemy子类实现不同的attack方法。 接下来是迭代器部分。Dungeon类需要实现一个迭代器,允许按顺序探索房间。这可以通过在Dungeon类中定义__iter__和__next__方法来实现,可能使用生成器或者维护当前的索引来遍历房间列表。 文件存储方面,save_system.py需要处理JSON的读写。这里需要将游戏状态(如玩家信息、地牢结构)转换为字典,再保存为JSON文件。加载时则相反,读取JSON并重建对象。同时要考虑异常处理,比如文件损坏或格式错误的情况。 异常处理部分,用户提到需要处理无效输入和损坏的存档文件。例如,在读取存档时,如果JSON结构不符合预期,应该引发自定义异常,并在主程序中捕获这些异常,给出友好的错误提示。 随机化方面,地牢地图、敌人和物品的生成需要随机。可能需要在Dungeon类的初始化时使用random模块来生成房间、连接,以及随机放置敌人和物品。 现在看项目结构中的各个文件: - player.py:Player类,处理玩家属性和物品管理。 - dungeon.py:Dungeon和Room类,负责地牢结构和房间连接。 - enemy.py:Enemy及其子类,不同敌人的行为。 - item.py:Item类及其子类,不同类型的物品效果。 - battle.py:战斗系统,处理玩家与敌人的战斗逻辑。 - save_system.py:存档和读档功能,使用JSON。 - main.py:主游戏逻辑,循环、输入处理等。 接下来需要为每个文件生成示例代码,确保覆盖所有概念。例如,在dungeon.py中,Dungeon类需要实现迭代器,Room类可能包含物品和敌人。在save_system.py中,使用json模块进行序列化和反序列化,处理可能的异常。 需要注意各模块之间的依赖关系,比如Dungeon可能需要引用Room,而Room可能包含Enemy和Item的实例。保存系统需要能够将对象转换为可序列化的字典结构,可能需要每个类实现to_dict方法,反之则用from_dict类方法重建对象。 异常处理方面,比如在加载存档时,如果数据缺失或类型错误,可以抛出CorruptedSaveFile异常,并在主程序中捕获,提示用户存档损坏。输入处理时,捕获无效命令,提示重新输入。 随机生成地牢时,Dungeon的初始化可能生成随机数量的房间,随机连接,并随机放置敌人和物品。敌人类型和物品类型也可以随机选择,比如使用random.choice从预设列表中选取。 测试代码是否符合要求,比如迭代器是否真的能逐个房间遍历,存档是否能正确保存和加载,战斗系统是否调用敌人的attack方法(多态)等。 最后,确保代码结构清晰,各模块分工明确,符合给定的项目结构。例如,战斗逻辑在battle.py中处理,而主循环在main.py中调用各个模块的功能。</think>Here's the organized code structure implementing the requested concepts: 1. **OOP Structure (player.py, dungeon.py, enemy.py, item.py)** ```python # player.py class Player: def __init__(self, name, health=100): self.name = name self.health = health self.inventory = [] def add_item(self, item): self.inventory.append(item) # dungeon.py class Room: def __init__(self, description, items=None, enemy=None): self.description = description self.items = items if items else [] self.enemy = enemy self.connections = {} class Dungeon: def __init__(self): self.rooms = [] self.current_room = 0 def __iter__(self): self.iter_index = 0 return self def __next__(self): if self.iter_index >= len(self.rooms): raise StopIteration result = self.rooms[self.iter_index] self.iter_index += 1 return result # enemy.py class Enemy: def __init__(self, name, health, damage): self.name = name self.health = health self.damage = damage def attack(self): return self.damage class Goblin(Enemy): def __init__(self): super().__init__("Goblin", 50, 10) # item.py class Item: def __init__(self, name, effect): self.name = name self.effect = effect class HealthPotion(Item): def __init__(self): super().__init__("Health Potion", 20) ``` 2. **JSON Save System (save_system.py)** ```python import json class SaveSystem: @staticmethod def save_game(player, dungeon, filename): data = { "player": { "name": player.name, "health": player.health, "inventory": [item.name for item in player.inventory] }, "dungeon": { "current_room": dungeon.current_room } } try: with open(filename, 'w') as f: json.dump(data, f) except IOError as e: raise SaveError(f"Failed to save game: {str(e)}") @staticmethod def load_game(filename): try: with open(filename) as f: data = json.load(f) return data except (IOError, json.JSONDecodeError) as e: raise LoadError(f"Failed to load game: {str(e)}") ``` 3. **Exception Handling** ```python class GameError(Exception): pass class SaveError(GameError): pass class LoadError(GameError): pass ``` 4. **Battle System (battle.py)** ```python class BattleSystem: @staticmethod def fight(player, enemy): while player.health > 0 and enemy.health > 0: enemy.health -= 10 # Player attack if enemy.health > 0: player.health -= enemy.attack() return player.health > 0 ``` 5. **Main Game Loop (main.py)** ```python from dungeon import Dungeon, Room from player import Player from save_system import SaveSystem, SaveError, LoadError def main(): player = Player("Hero") dungeon = Dungeon() try: # Game initialization and loop while True: # Game logic here pass except KeyboardInterrupt: print("\nGame interrupted") except (SaveError, LoadError) as e: print(f"Error: {str(e)}") ``` **Implementation Notes:** 1. **OOP & Inheritance**: Classes organized with clear inheritance hierarchy (Enemy->Goblin, Item->HealthPotion) 2. **Iterator Pattern**: Dungeon implements iterator protocol for room traversal 3. **JSON Handling**: SaveSystem manages serialization with error handling 4. **Exception Hierarchy**: Custom exceptions provide clear error contexts 5. **Randomization**: (Add to Dungeon initialization) random room generation/enemy placement
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值