Warning: ftp_fget() expects parameter 1 to be resource, null given in /www/wwwroot/new.weijing.co/wp-admin/includes/class-wp-filesystem-ftpext.php on line 146

在 Python 中抛出异常以及相关应用场景

当 Python 试图执行无效代码时,就会抛出异常。
我们也可以使用 raise 语句抛出异常。在代码中, raise 语句包含以下部分:

  • raise 关键字;
  • 调用 Exception 函数,同时传入出错信息描述。
raise Exception(\'抛出异常\')

Al Sweigart 写过这样一个示例,很好地诠释了抛出异常用法。Sweigart 定义了一个 box_print() 函数,它接受一个字符、一个宽度和一个高度作为入参。然后按照指定的宽度和高度,使用该字符创建了一个小盒子的图像。最后把这个盒子打印到屏幕上。

def box_print(symbol, width, height):
    if len(symbol) != 1:
        raise Exception(\'Symbol must be a single character string.\')
    if width <= 2:
        raise Exception(\'Width must be greater than 2.\')
    if height <= 2:
        raise Exception(\'Height must be greater than 2.\')
    print(symbol * width)
    for i in range(height - 2):
        print(symbol + (\' \' * (width - 2)) + symbol)
    print(symbol * width)
for sym, w, h in ((\'*\', 4, 4), (\'O\', 20, 5), (\'x\', 1, 3), (\'ZZ\', 3, 3)):
    try:
        box_print(sym, w, h)
    except Exception as err:
        print(\'An exception happened:\' + str(err))

运行结果:

该函数希望输入的字符长度大于 0,并且宽度和高度要大于 2,否则抛出异常。除此之外,还使用了以下技巧:

  • 使用 * 符号来实现复制多个空格。
  • 使用 for in 方法来初始化元组数据。
  • 还使用了 except 语句的 except Exception as err 形式,如果 box_print() 返回一个 Exception 对象,那么这条语句就会将它保存在名为 err 的变量中。

使用 try 和 except 语句,我们可以从容使用更优雅的方式来处理错误。

发表评论

您的电子邮箱地址不会被公开。

Shopping Cart