Python面向对象编程-自定义异常使用(一)
2023-06-13 09:18:43 时间
自定义异常可用于多种目的。
定义文件时,当文件的格式不正确时,我们可以抛出自定义异常来指示错误。
- 在编写网络应用程序时,如果网络请求失败,我们可以抛出自定义异常来指示错误。
- 在编写数据库应用程序时,如果数据库连接失败,我们可以抛出自定义异常来指示错误。
- 在编写游戏时,如果玩家尝试在不允许的情况下执行某个操作,我们可以抛出自定义异常来指示错误。
下面是一个使用自定义异常的示例,它演示了如何在游戏中处理玩家错误操作:
class InvalidMoveError(Exception):
def __init__(self, message):
self.message = message
class Game:
def __init__(self):
self.board = [['', '', ''] for i in range(3)]
self.current_player = 'X'
def display_board(self):
for row in self.board:
print(row)
def make_move(self, row, col):
if row < 0 or row > 2 or col < 0 or col > 2:
raise InvalidMoveError("Invalid move. Please choose a row and column between 0 and 2.")
if self.board[row][col] != '':
raise InvalidMoveError("Invalid move. That square is already taken.")
self.board[row][col] = self.current_player
if self.current_player == 'X':
self.current_player = 'O'
else:
self.current_player = 'X'
def is_game_over(self):
for i in range(3):
if self.board[i][0] == self.board[i][1] == self.board[i][2] != '':
return True
if self.board[0][i] == self.board[1][i] == self.board[2][i] != '':
return True
if self.board[0][0] == self.board[1][1] == self.board[2][2] != '':
return True
if self.board[0][2] == self.board[1][1] == self.board[2][0] != '':
return True
return False
game = Game()
while not game.is_game_over():
game.display_board()
row = int(input("Enter row (0-2): "))
col = int(input("Enter column (0-2): "))
try:
game.make_move(row, col)
except InvalidMoveError as e:
print("Error:", e.message)
game.display_board()
print("Game over!")
上面的示例中,我们定义了一个名为 Game
的游戏类,用于处理棋盘和游戏规则。我们还定义了一个名为 InvalidMoveError
的自定义异常,用于处理玩家的无效移动。
在 make_move
方法中,如果玩家选择了无效的行或列,则抛出 InvalidMoveError
。如果玩家选择了已经被占用的方格,则也会抛出 InvalidMoveError
。在 while
循环中,我们不断调用 make_move
方法,并在出现异常时捕获和处理异常。在异常处理程序中,我们将打印错误消息,告诉用户出现了什么错误。
相关文章
- python skitlearn_Python sklearn
- python win32api messagebox_如何在Python中使用Win32 API?
- mt4 python_一个使用Python自动化交易外汇MT4脚本实现「建议收藏」
- python fileinput_Python之fileinput模块学习「建议收藏」
- Python入门系列(五)一篇搞懂python语句
- python监控网页内容变化_使用Python监控文件内容变化代码实例
- 【说站】python raise语句重新抛出异常
- Python标识符的命名规则,下列哪些是对的?_python标识符不能使用关键字
- [Python]异常处理「2」
- python自定义异常的简单使用
- Python保存json_python保存json文件
- python django 数据库_Apache+Mysql+PHP/Python简单项目
- python抛出异常写法_零基础学 Python(32):如何抛出和捕获异常?「建议收藏」
- python hexdump_笨办法学 Python · 续 练习 26:`hexdump`
- python type error是什么意思_Python 报错 TypeError:’DoesNotExist’对象不可调用
- python-异常处理和错误调试-asyncio中的错误调试(一)
- python-Python与MySQL数据库-使用Python执行MySQL查询
- python-Python与SQLite数据库-使用Python执行SQLite查询(二)
- python-Python与MongoDB数据库-使用Python执行MongoDB查询(二)
- 使用Python执行Linux命令的方法(python调用linux命令)
- 使用Python编程连接MySQL数据库(python连mysql)
- Python输出函数print()总结(python print())详解编程语言
- 使用Python连接SQL Server数据库(python连接sqlserver数据库)
- Python 3.3 为改进代码中的异常处理所做的工作
- python驱动使用pip安装MySQL Python驱动的简单步骤(pip安装mysql)
- Python编程连接MySQL:从零开始(python与mysql)
- Python中使用异常处理来判断运行的操作系统平台方法