��O

��O���g�����R

��O�̊�b

try/except/else

try:
    <statements>        # ���s
except <name>:          # ��O name ������
    <statements>
except: <name>, <data>: # name �ɒlj��� data
    <statements>
else:
    <statements>        # ��O���������Ȃ������Ƃ�

try/finally

try:
    <statements>
finally:
    <statements>        # ��n��

raise

raise <name>
raise <name>, <data>

�f�t�H���g�̓���

bad.py�����s.
>>> import bad
Traceback (most recent call last):
  File "", line 1, in ?
    import bad
  File "C:\home\papa\lips\prog-method\bad.py", line 7, in ?
    gosouth(1)
  File "C:\home\papa\lips\prog-method\bad.py", line 5, in gosouth
    print gobad(x, 0)
  File "C:\home\papa\lips\prog-method\bad.py", line 2, in gobad
    return x / y
ZeroDivisionError: integer division or modulo by zero
�̂悤�ɗ�O(�G���[)�������������_����k���ČĂяo���Ă����֐���\������. (stack trace)

�g�ݍ��ݗ�O�̕ߑ�

>>> def kaboom(list, n):
	print list[n]

	
>>> try:
	kaboom([0, 1, 2], 3)
except IndexError:
	print 'Hello world!'

	
Hello world!

���[�U��`�̗�O�̔����ƕߑ�

>>> MyError = "my error"
>>> def stuff(file):
	raise MyError

>>> file = open('bad.py', 'r')
>>> try:
	stuff(file)
finally:
	file.close()

	
Traceback (most recent call last):
  File "", line 2, in ?
    stuff(file)
  File "", line 2, in stuff
    raise MyError
my error
>>> file.read()
Traceback (most recent call last):
  File "", line 1, in ?
    file.read()
ValueError: I/O operation on closed file
>>> file = open('bad.py', 'r')
>>> stuff(file)
Traceback (most recent call last):
  File "", line 1, in ?
    stuff(file)
  File "", line 2, in stuff
    raise MyError
my error
>>> file.read()
'def gobad(x, y):\n    return x / y\n\ndef gosouth(x):\n    print gobad(x, 0)\n\ngosouth(1)\n'
try/finally ���g�����ŏ��̗�ł́A�G���[�̌�� file ���‚����Ă���̂ŁA file.read() �����s���邪�A2�Ԗڂ̂悤�� stuff() �𒼐ڌĂ񂾏ꍇ�ɂ́A file ���J�����܂܂Ȃ̂ŁAfile.read()����������B

���K���

  1. oops �Ƃ����֐����쐬����B���̊֐����Ăяo���ƁAIndexError ��O�� �����I�ɋN���������̂Ƃ���B ���ɁAtry/except ���̓����� oops ���Ăяo���ʂȊ֐����쐬���A ���̃G���[��ߑ�����B oops �֐��ɂ���ċN��������O�� IndexError ���� KeyError �ւ� �ύX�����ꍇ�A�ǂ��Ȃ邾�낤���B
  2. �֐��ŋ��ȏ��Ƃ͕ʂɏo�����A�񎟕������̉���Ԃ��֐��ŁA ���ʎ������̏ꍇ�ƕ��̏ꍇ�Ƃ𕪂������낤���H if/else ���g���Ă�����Atry/except �ŏ��������Ă݂�B