2022年 11月 5日

python抛出异常

当 Python 试图执行无效代码时,就会抛出异常。在第 3 章中,你已看到如何使用 try 和 except 语句来处理 Python 的异常,这样程序就可以从你预期的异常中恢复。但你也可以在代码中抛出自己的异常。抛出异常相当于是说:“停止运行这个函数中的代码,将程序执行转到 except 语句 ”。抛出异常使用 raise 语句。在代码中,raise 语句包含以下部分:
• raise 关键字;
• 对 Exception 函数的调用;
• 传递给 Exception 函数的字符串,包含有用的出错信息。
例如,在交互式环境中输入以下代码:

  1. >>> raise Exception('This is the error message.')
  2. Traceback (most recent call last):
  3. File "<pyshell#191>", line 1, in <module>
  4. raise Exception('This is the error message.')
  5. Exception: This is the error message.

如果没有 try 和 except 语句覆盖抛出异常的 raise 语句,该程序就会崩溃,并显示异常的出错信息。通常是调用该函数的代码知道如何处理异常,而不是该函数本身。所以你常会看到 raise 语句在一个函数中,try 和 except 语句在调用该函数的代码中。例如,
打开一个新的文件编辑器窗口,输入以下代码,并保存为 boxPrint.py:

  1. def boxPrint(symbol, width, height):
  2. if len(symbol) != 1:
  3. raise Exception('Symbol must be a single character string.')
  4. if width <= 2:
  5. raise Exception('Width must be greater than 2.')
  6. if height <= 2:
  7. raise Exception('Height must be greater than 2.')
  8. print(symbol * width)
  9. for i in range(height - 2):
  10. print(symbol + (' ' * (width - 2)) + symbol)
  11. print(symbol * width)
  12. for sym, w, h in (('*', 4, 4), ('0', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
  13. try:
  14. boxPrint(sym, w, h)
  15. except Exception as err:
  16. print('An exception happened: ' + str(err))

这里我们定义了一个 boxPrint() 函数,它接受一个字符、一个宽度和一个高度。它按照指定的宽度和高度,用该字符创建了一个小盒子的图像。这个盒子被打印到屏幕上。假定我们希望该字符是一个字符,宽度和高度要大于 2。我们添加了 if 语句,如果这些条件没有满足,就抛出异常。稍后,当我们用不同的参数调用 boxPrint()时,try/except 语句就会处理无效的参数。这个程序使用了 except 语句的 except Exception as err 形式。如果 boxPrint()返回一个 Exception 对象,这条语句就会将它保存在名为 err 的变量中。Exception 对象可以传递给str(),将它转换为一个字符串,得到用户友好的出错信息。运行 boxPrint.py,输出看起来像这样:

  1. ****
  2. * *
  3. * *
  4. ****
  5. OOOOOOOOOOOOOOOOOOOO
  6. O O
  7. O O
  8. O O
  9. OOOOOOOOOOOOOOOOOOOO
  10. An exception happened: Width must be greater than 2.
  11. An exception happened: Symbol must be a single character string.

使用 try 和 except 语句,你可以更优雅地处理错误,而不是让整个程序崩溃。