#!/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域来为用户打印一个恰当的消息。对象