#!/usr/bin/python class ShortInputException(Exception): #自定義的異常類 '''A user-defined exception class.''' def init(self, length, atleast): Exception.init(self) self.length = length self.atleast = atleastpython
try: s = raw_input('Enter something --> ') if len(s) < 3: raise ShortInputException(len(s), 3) #raise 自定義的異常類 # Other work can continue as usual here except EOFError: print '\nWhy did you do an EOF on me?' except ShortInputException, x: print 'ShortInputException: The input was of length %d,
was expecting at least %d' % (x.length, x.atleast) else: print 'No exception was raised.'
這裏,咱們建立了咱們本身的異常類型,其實咱們可使用任何預約義的異常/錯誤。這個新的異常類型是ShortInputException類。它有兩個域——length是給定輸入的長度,atleast則是程序指望的最小長度。函數
在except從句中,咱們提供了錯誤類和用來表示錯誤/異常對象的變量。這與函數調用中的形參和實參概念相似。在這個特別的except從句中,咱們使用異常對象的length和atleast域來爲用戶打印一個恰當的消息。對象