python 第8章 异常处理


Python 用异常对象来表示异常,遇到错误会引发异常程序回溯。python已经建立了许多的异常类方法,用户自己也建立自己异常类型

8.2.1 raise语句

如果不是继承的Exception的类或方法,想处理异常就需要借助raise语句

>>> raise "The information of error"

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    raise "The information of error"
TypeError: exceptions must be old-style classes or derived from BaseException, not str
>>>

>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']

8.3 捕捉异常


>>> x = input()
10
>>> y = input()
0
>>> try:
	z=x/y
	print z
except ZeroDivisionError:
	print "The num is zero!!!"

	
The num is zero!!!

屏蔽异常

class MuffledCalculator:
    muffled = False
    def calc(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print 'illegal divided by zero'
            else:
                raise

z = MuffledCalculator()
z.muffled = True
print z.calc("6/0")
z.muffled = False
print z.calc("6/0")

>>> 
illegal divided by zero
None


Traceback (most recent call last):
  File "G:/New Knowledge/practice/python/test.py", line 16, in <module>
    print z.calc("6/0")
  File "G:/New Knowledge/practice/python/test.py", line 5, in calc
    return eval(expr)
  File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 

class MuffledCalculator:
    muffled = False
    def calc(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print 'illegal divided by zero'
            else:
                raise
        except (TypeError,NameError),e:
            print e

z = MuffledCalculator()
z.muffled = True
print z.calc("6/0")
z.muffled = False
print z.calc("7/3")
print z.calc("count")
>>> 
illegal divided by zero
None
2
name 'count' is not defined
None
>>> 

def cal(x,y):
	try:
		print x/y
	except NameError:
		print "unknown name"
	except ZeroDivisionError:
		print 'zero divided'
	else:
		print "go on well"
	finally:
		print "cleaning up"

>>> cal(4,3)
1
go on well
cleaning up
>>> cal(4,0)
zero divided
cleaning up
>>> cal('3','sd')
cleaning up


Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    cal('3','sd')
  File "<pyshell#43>", line 3, in cal
    print x/y
TypeError: unsupported operand type(s) for /: 'str' and 'str'
>>> 

异常传递:

def faulty():
    raise Exception('Someting is wrong!!!')
def ignore_exception():
    faulty()
def handle_exception():
    try:
        faulty()
    except:
        print 'error in handle'

handle_exception()
ignore_exception()

error in handle


Traceback (most recent call last):
  File "G:/New Knowledge/practice/python/test.py", line 12, in <module>
    ignore_exception()
  File "G:/New Knowledge/practice/python/test.py", line 4, in ignore_exception
    faulty()
  File "G:/New Knowledge/practice/python/test.py", line 2, in faulty
    raise Exception('Someting is wrong!!!')
Exception: Someting is wrong!!!
>>> 

8.11 运用异常:

def describePerson1(person):
    print "Description of ",person['name']
    print 'age:%(age)s'%person
    if 'Occupation' in person:
        print 'Occupation:%(Occupation)s'%person

def describePerson2(person):
    print "Description of ",person['name']
    print 'age:%(age)s'%person
    try:
        print 'Occupation:%(Occupation)s'%person
    except:pass

d = {'name':'John','age':15,'Occupation':'student'}
t = {'name':'John','age':15}
describePerson1(d)
describePerson1(t)
describePerson2(d)
describePerson2(t)

使用异常,效率更高

>>> 
Description of  John
age:15
Occupation:student
Description of  John
age:15
Description of  John
age:15
Occupation:student
Description of  John
age:15
>>> 





posted @ 2014-05-03 11:23  剑不飞  阅读(331)  评论(0编辑  收藏  举报