���� Python �̳�
��13�� �쳣
��һҳ �����쳣 ��һҳ

�����쳣

�����ʹ��raise��� ���� �쳣���㻹��ָ������/�쳣�����ƺͰ����쳣 ������ �쳣��������������Ĵ�����쳣Ӧ�÷ֱ���һ��Error��Exception���ֱ�ӻ��ӵ����ࡣ

��������쳣

��13.2 ��������쳣

#!/usr/bin/python
# Filename: raising.py


class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast


try:
    s =
raw_input('Enter something --> ')
    if len(s) < 3:
        raise ShortInputException(
len(s), 3)
    # Other work can continue as usual here
except EOFError:
    print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
    print 'ShortInputException: The input was of length %d, \
          was expecting at least %d'
% (x.length, x.atleast)
else:
    print 'No exception was raised.'

Դ�ļ���code/raising.py��

���

$ python raising.py
Enter something -->
Why did you do an EOF on me?

$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3

$ python raising.py
Enter something --> abc
No exception was raised.

������

������Ǵ����������Լ����쳣���ͣ���ʵ���ǿ���ʹ���κ�Ԥ������쳣/��������µ��쳣������ShortInputException�ࡣ���������򡪡�length�Ǹ�������ij��ȣ�atleast���dz�����������С���ȡ�

��except�Ӿ��У������ṩ�˴������������ʾ����/�쳣����ı��������뺯�������е��βκ�ʵ�θ������ơ�������ر��except�Ӿ��У�����ʹ���쳣�����length��atleast����Ϊ�û���ӡһ��ǡ������Ϣ��


��һҳ ��һ�� ��һҳ
try..except ��ҳ try..finally