異常處理方法一般為:
try: ------code----- except Exception as e: # 拋出異常之后將會執行 print(e) else: # 沒有異常將會執行 print('no Exception') finally: # 有沒有異常都會執行 print('execute is finish')
可以用 raise 拋出一個異常,以下是一個輸入字符太短的異常例子:
class ShortInputException(Exception): '''自定義異常類''' def __init__(self, length, atleast): self.length = length self.atleast = atleast try: s = input('please input:') if len(s) < 3: raise ShortInputException(len(s), 3) except ShortInputException as e: print('輸入長度是%s,長度至少是%s' %(e.length, e.atleast)) else: print('nothing...')
如果輸入字符長度小於3,那么將會拋出 ShortInputException 異常:
>>> please input:qw
輸入長度是2,長度至少是3
注意 如果異常處理時 再次 使用 raise 后面什么都沒有,那么代表把這個異常還給系統,讓解釋器用默認的方式處理它.