python中的异常处理
主要用到 try...except...raise...finally...
1. try...except...
try: for i in range(1, 1000): print i time.sleep(1) except KeyboardInterrupt: print 'My Interruption'
2. try...except...finally...(中途不论是否有异常,finally语句都会执行)
try: for i in range(1, 1000): print i time.sleep(1) except KeyboardInterrupt: print 'My Interruption' finally: print 'Exit'
3. try...raise...
try: for i in range(1, 1000): print i time.sleep(1) if i == 5: raise KeyboardInterrupt('Interruption') except KeyboardInterrupt: print 'My Interruption' finally: print 'Exit'
以上只执行except和finally语句
try: for i in range(1, 1000): print i time.sleep(1) if i == 5: raise KeyboardInterrupt('Interruption') #except KeyboardInterrupt: #print 'My Interruption' finally: print 'Exit'
以上只执行raise语句