小白教程

 找回密码
 立即注册

引发异常

发布者: 小白教程

你可以提高使用异常raise提供的错误/异常的名称和异常对象将被声明抛出

您可能引发的错误或异常应该是一个类,该类必须直接或间接地是该类的派生Exception类。

示例(另存为exceptions_raise.py):

class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    text = input('Enter something --> ')
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
    # Other work can continue as usual here
except EOFError:
    print('Why did you do an EOF on me?')
except ShortInputException as ex:
    print(('ShortInputException: The input was ' +
           '{0} long, expected at least {1}')
          .format(ex.length, ex.atleast))
else:
    print('No exception was raised.')

输出:

$ python exceptions_raise.py
Enter something --> a
ShortInputException: The input was 1 long, expected at least 3

$ python exceptions_raise.py
Enter something --> abc
No exception was raised.

这个怎么运作

在这里,我们正在创建我们自己的异常类型。这种新的异常类型称为ShortInputException它有两个字段-length这是给定输入的长度,atleast这是程序期望的最小长度。

except子句中,我们提到了错误的类别,该类别将存储as在变量名中,以保存相应的错误/异常对象。这类似于函数调用中的参数和自变量。在此特定except子句中,我们使用异常对象lengthatleast字段向用户打印适当的消息。

尝试...最后

假设您正在读取程序中的文件。无论是否引发异常,如何确保文件对象正确关闭?可以使用该finally来完成

将该程序另存为exceptions_finally.py

import sys
import time

f = None
try:
    f = open("poem.txt")
    # Our usual file-reading idiom
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print(line, end='')
        sys.stdout.flush()
        print("Press ctrl+c now")
        # To make sure it runs for a while
        time.sleep(2)
except IOError:
    print("Could not find file poem.txt")
except KeyboardInterrupt:
    print("!! You cancelled the reading from the file.")
finally:
    if f:
        f.close()
    print("(Cleaning up: Closed the file)")

输出:

$ python exceptions_finally.py
Programming is fun
Press ctrl+c now
^C!! You cancelled the reading from the file.
(Cleaning up: Closed the file)

这个怎么运作

我们进行通常的文件读取工作,但是我们使用time.sleep函数在每行打印后任意引入了2秒钟的睡眠时间,以使程序运行缓慢(Python本质上是非常快的)。当程序仍在运行时,按ctrl + c中断/取消程序。

观察到KeyboardInterrupt引发异常,程序退出了。但是,在程序退出之前,将执行finally子句,并且文件对象始终处于关闭状态。

请注意,PythonNone会考虑分配值为0的变量或为空序列或集合的变量False这就是为什么我们可以if f:在上面的代码中使用它的原因

还要注意,我们使用sys.stdout.flush()after,print以便它立即打印到屏幕上。

上一篇:异常情况下一篇:with语句

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 01:46 , Processed in 0.020460 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部