位置:首页 > 软件操作教程 > 编程开发 > Python > 问题详情

python 异常

提问人:杨紫红发布时间:2020-11-20

当程序中出现某些异常的状况时,异常就发生了。python中可以使用try ... except 处理。

try:

    print 1/0

except ZeroDivisionError, e:

    print e

except:

    print "error or exception occurred."


#integer division or modulo by zero


  可以让try ... except 关联上一个else,当没有异常时则执行else。


  我们可以定义自己的异常类,需要继承Error或Exception。

class ShortInputException(Exception):

    '''A user-defined exception class'''

    def __init__(self, length, atleast):

        Exception.__init__(self)

        self.length = length

        self.atleast = atleast

try:

    s = raw_input("enter someting-->")

    if len(s) < 3:

        raise ShortInputException(len(s), 3)

except EOFError:

    print "why you input an EOF?"

except ShortInputException, ex:

    print "The lenght of input is %d, was expecting at the least %d" % (ex.length, ex.atleast)

else:

    print "no exception"

#The lenght of input is 1, was expecting at the least 3


  try...finally

try:

    f = file("test.txt")

    while True:

        line = f.readline()

        if len(line) == 0:

            break

        time.sleep(2)

        print line,

finally:

    f.close()

    print "Cleaning up..."

继续查找其他问题的答案?

相关视频回答
回复(0)
返回顶部