我想知道抛出异常是否是向用户传达内容的最佳方式,以防用户是另一个程序员。
我正在开发一个小型库来创建基于文本的游戏(想想矮人堡垒,但非常简单)。当然,我希望东西在地图内移动。它非常简单,文档字符串非常完整,因此应该很好地阅读。
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
这种结构不好吗?我认为它读得很好:当用户试图移动他自己的一块时,他可以这样做:
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
在库中实现了更多逻辑,其中代码尝试执行某些操作但如果不能,则会抛出异常。这个可以吗?或者我应该返回错误代码(例如整数)。
答案 0 :(得分:3)
此用例似乎可以用于例外。有人说:
"例外应该是例外情况"
但是在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
答案 1 :(得分:2)
在我看来,抛出异常是告知发生某些错误的更好方法。特别是如果你的函数没有返回任何值。想象一下,每次调用后开发人员都必须检查返回值的类型。它更加清晰。 检查this。