開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART VII.(Exceptions and Tools)、CHAPTER 33(Exception Basics)、Test Your Knowledge: Quiz 1, 2, 3, 4, 5.を解いてみる。
その他参考書籍
Test Your Knowledge:
-
- Error handling
- Event notification
- Special-case handling
-
Default Exception Handlerが呼び出される。
コード(BBEdit)
sample.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- # IndexError print([1][1])
入出力結果(Terminal)
$ ./sample.py Traceback (most recent call last): File "./sample.py", line 4, in <module> print([1][1]) IndexError: list index out of range $
-
try/exceptを使えばいい。
コード(BBEdit)
sample.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- try: print([1][1]) except IndexError: print('IndexError') print('after index error')
入出力結果(Terminal)
$ ./sample.py IndexError after index error $
-
- raise
- assert
コード(BBEdit)
sample.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- class A(Exception): pass try: raise A() except A: print('raise') try: assert(False) except: print('False assert') try: assert(True) except: print('True assert') print('after raise, assert') assert(True) print('True') assert(False) print('False')
入出力結果(Terminal)
$ ./sample.py raise False assert after raise, assert True Traceback (most recent call last): File "./sample.py", line 23, in <module> assert(False) AssertionError $
-
- try/finally
- with/as
コード(BBEdit)
sample.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- def func(x, i): try: print(x[i]) finally: print('finally') func([1], 0) func([1], 1)
入出力結果(Terminal)
$ ./sample.py 1 finally finally Traceback (most recent call last): File "./sample.py", line 11, in <module> func([1], 1) File "./sample.py", line 6, in func print(x[i]) IndexError: list index out of range $
0 コメント:
コメントを投稿