例外処理 on Python
- Ubuntu 10.10
Python 2.6
■プログラム(TestError.py)
#! /usr/bin/env python # coding:utf-8 class TestError(object): ''' 例外処理 ''' def __init__(self): ''' 変数初期化 ''' self.nums = [1, 2, 3, 4, 5] self.strs = ["a", "b", "c", "d", "e"] def testErr1(self): ''' 例外処理なし。エラーになる ''' print self.nums[10] def testErr2(self): ''' 例外処理 ''' try: print self.nums[10] except: print 'エラー' def testErr3(self): ''' 例外の種類で処理を分ける ''' try: print self.nums[0] + self.strs[0] except TypeError: print '型がちがう!' except IndexError: print 'インデックスが違う!' def testErr4(self): ''' 例外の詳細を調べる ''' try: print self.nums[10] except IndexError, e: print e.args[0] def testErr5(self): ''' 例外が発生しなかった場合の処理 ''' try: print self.nums[0] except: print "例外あり" else: print "例外なし" def testErr6(self): ''' 例外処理後、必ず処理を実行する ''' try: print self.nums[10] except: print "ERROR" finally: print "ファイルクローズ処理など" def testErr7(self, x): ''' 例外を発生させる ''' if x > 5: raise ValueError, ('5以下を指定して!', x) def testErr8(self, x): ''' 例外の再通知 ''' try: print self.nums[x] except Exception, e: raise IndexError, '5以下を指定して!' def testErr9(self): ''' 作成した例外を通知 ''' raise MyError class MyError(Exception): ''' 例外を作成する ''' msg = "作成された例外" if __name__ == "__main__": err = TestError() # err.testErr1() # 出力結果 #Traceback (most recent call last): # File "/home/yunmaru/work/workspace/fcms/ref/TestError.py", line 25, in <module> # err.testErr1() # File "/home/yunmaru/work/workspace/fcms/ref/TestError.py", line 19, in testErr1 # print self.nums[10] #IndexError: list index out of range err.testErr2() # エラー err.testErr3() # 型がちがう! # 組み込みの例外を取得する(美しくない) # filter(lambda x: True if str(x).find("Error") != -1 else False, dir(__builtins__)) # PyDevで見るなら。 # for err in filter(lambda x: True if str(x).find("Error") != -1 else False, dir(__builtins__)): print err # ライブラリ参照 # http://docs.python.org/library/exceptions.html#exception-hierarchy err.testErr4() # list index out of range err.testErr5() # 例外なし err.testErr6() # ERROR \n ファイルクローズ処理など try: err.testErr7(6) except Exception, e: print '%s: %d' % e.args # 5以下を指定して!: 6 try: err.testErr8(10) except Exception, e: print e # 5以下を指定して! try: err.testErr9() except MyError, e: print e.msg