k0b0's record.

Computer Engineering, Arts and Books

Python入門 例外処理

例外処理

 pythonの例外処理についてメモ。

書式

try:
    処理
except [expression]:  
    # In case of [expression]
    処理
except:                        
    # For other exceptions
    処理
else:                           
    # If no exception occurs
    処理
finally:                         
    # A block that always runs.
    処理

例外処理の記述例(test_except.py)

#test_except
def test_except():
    str = 'Test except.'
    try:
        print(str[20])
    except IOError:         
        print('IOError')
    except IndexError:      
        print('IndexError')
    except:
        print('Unknown')    
    else:
        print('Other')     
    finally:
        print('Finally')    

if (__name__=='__main__'):
    test_except() # Call test_except()

実行結果

 上記のプログラムでは配列strのインデックス外にアクセスする記述があるため、例外IndexErrorが呼び出されている。また、finallyブロックは常に実行されるため、その処理結果が実行結果に反映されている。

IndexError
Finally