位置:首頁 > 軟件操作教程 > 編程開發(fā) > Python > 問題詳情

python 異常

提問人:楊紫紅發(fā)布時(shí)間:2020-11-20

當(dāng)程序中出現(xiàn)某些異常的狀況時(shí),異常就發(fā)生了。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 關(guān)聯(lián)上一個(gè)else,當(dāng)沒有異常時(shí)則執(zhí)行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..."

繼續(xù)查找其他問題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部