拋出異常

from pip._vendor.distlib.compat import raw_input
class ShortInputException(Exception):
    '''你定義的異常類。'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    s = raw_input('請輸入 --> ')

    if len(s) < 3:
        # raise引起一個你定義的異常
        raise ShortInputException(len(s), 3)

except EOFError:
    print ('/n你輸入了一個結束標記EOF')
except ShortInputException, x:#x這個變量被綁定到了錯誤的實例
    print('ShortInputException: 輸入的長度是 %d,長度至少應是 %d'% (x.length, x.atleast))
else:
    print ('沒有異常發生.')

 

運行結果:python

$ python raising.py
    請輸入 -->
    你輸入了一個結束標記EOF

    $ python raising.py
    請輸入 --> --> ab
    ShortInputException: 輸入的長度是 2, 長度至少應是 3

    $ python raising.py
    請輸入 --> abc
    沒有異常發生.
相關文章
相關標籤/搜索