Python:在此示例中抛出异常是正确的用例吗?

标签 python python-3.x exception

我想知道抛出异常是否是与用户沟通的最佳方式,以防用户是另一个程序员。

我正在开发一个小型库来创建基于文本的游戏(想想矮人要塞,但极其简单)。当然,我希望东西能在 map 内移动。它非常简单,文档字符串也非常完整,所以读起来应该很好。

def move(self, tile):
    """Move the object to a tile.
    That means: unlink the piece from its current tile and link it
    to the new tile.

    Raise CharacterIsNotOnATileError if piece didn't already
    have an associated tile, CharacterIsNotOnThisBoardError if
    the destinity tile is not on the same board as the current tile,
    OutOfBoard error if destinity tile is falsey (most probably
    this means you're tring to move somewhere outside the map)
    """
    if tile.piece is not None:
        raise PositionOccupiedError(tile)
    if not self.home_tile:
        raise PieceIsNotOnATileError
    if self.home_tile.board is not tile.board:
        raise PieceIsNotOnThisBoardError
    if not tile:
        raise OutOfBoardError

    self.home_tile.piece = None
    tile.piece = self

这个结构不好吗?我认为它读起来很好:当用户尝试移动自己的一 block 时,他可以这样做:

try:
    character.move(somewhere)
except PositionOcuppiedError:
    character.punish  # cause i'm in hardcore
except OutOfBoardError:
    character.kill  # cause we were in a floating world and the
                    # character just fell off

库中还有一些像这样实现的逻辑,其中代码尝试做某事,但如果不能,则会抛出异常。这个可以吗?或者也许我应该返回错误代码(例如,作为整数)。

最佳答案

这个用例似乎适合异常(exception)。有人说:

"Exceptions should be exceptional"

但在 Python 中,使用异常来执行流程控制并不被视为不好的做法(了解更多 "Is it a good practice to use try except else in python" )。

此外,请注意,如果将异常放置在重复调用的函数中,则在 Python 中抛出和检查异常可能会对性能产生负面影响。除非您正在开发一款有数百名玩家的快节奏游戏,否则这不应该是您主要关心的问题。您可以阅读更多关于捕获异常的性能相关问题in this topic on Stack Overflow .

就我个人而言,作为一名程序员,我宁愿处理异常(在使用 Python 编程时),也不愿处理错误代码或类似的东西。另一方面,如果返回的状态以错误代码的形式给出,那么处理它们并不困难——您仍然可以模仿 switch-case 构造,例如使用dictionary with callable handlers as values .

关于Python:在此示例中抛出异常是正确的用例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38851047/

相关文章:

java - 使用 JTabbedPane 时抛出异常

python - 捕获异常并将其输出到 django 的消息系统

java - 为什么我的异常需要放在 try/catch 中?

python - brew 更新后 virtualenv 损坏

python - 如何在 matplotlib 中绘制曲线图

excel - Python合并多个Excel表格形成汇总表

python - Python 类中的类型检查

python - 在python中将MAC地址转换为字节数组

python - odoo 导入 .xlsx 销售订单、购买订单

python - pop() empty deque() 逻辑