I wonder is if throwing exceptions is the best way to communicate something to the user, in case the user is another programmer.
I'm developing a small library to create text-based games (think Dwarf Fortress, but extremely more simple). Of course, I want stuff to move inside the map. It's very simple and the docstring is very complete, so it should read nicely.
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
Is this structure bad? I think it reads nicely: when the user tries to move a piece of his own, he can do:
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
There's some more logic in the library implemented like this, where the code tries to do something but if it can't, it will throw an exception. Is this OK? Or maybe I should be returning error codes (as integers, for example).