MicroPython メモ 12 / 例外処理

参考: Programming the BBC micro:bit: Getting Started with MicroPython, p.68-69
 
これだとインデックスが 5 を超えたところでエラーが出てプログラムが停止してしまう (Lua だと、存在しない要素を参照したときは nil が返ってくる)。

list = [0, 1, 2, 3, 4, 5]

i = 0
while True:
    print(list[i])
    i += 1

f:id:ti-nspire:20171224110337p:plain
 
例外処理は下のように try ブロック、 except ブロックを使う。

list = [0, 1, 2, 3, 4, 5]

try:
    i = 0
    while True:
        print(list[i])
        i += 1

except:
    print("exception thrown")

f:id:ti-nspire:20171224110824p:plain