python中的异常类型处理
2015-02-11 22:03
477 查看
3、异常和函数
在函数内引发异常时,它就会被传播到到函数调用的地方(对于方法也是一样的)
可以看到,faulty中产生的异常通过faulty和ignore_exception传播,最终导致了堆栈跟踪。同样地,它也传播了handle_exception,但在这个函数中被try/except语句处理。
注:这里在打印职业时,使用加号而不是逗号。否则字符串'Occupaton:'在异常引发之前就会被输出。
查看某对象是否有write属性
在函数内引发异常时,它就会被传播到到函数调用的地方(对于方法也是一样的)
>>> def faulty(): raise Exception('Something is wrong') >>> def ignore_expection(): faulty() >>> def handle_excepton(): try: faulty() except: print 'Exception handled' >>> ignore_expection() Traceback (most recent call last): File "<pyshell#252>", line 1, in <module> ignore_expection() File "<pyshell#245>", line 2, in ignore_expection faulty() File "<pyshell#242>", line 2, in faulty raise Exception('Something is wrong') Exception: Something is wrong
可以看到,faulty中产生的异常通过faulty和ignore_exception传播,最终导致了堆栈跟踪。同样地,它也传播了handle_exception,但在这个函数中被try/except语句处理。
>>> def describePerson(person): print 'Description of',person['name'] print 'Age:',person['age'] try: print 'Occupation:',person['occupation'] except KeyError: pass >>> describePerson({'name':'Throatwobbler','age':42}) Description of Throatwobbler Age: 42 Occupation: >>>
>>> def describePerson(person): print 'Description of',person['name'] print 'Age:',person['age'] try: print 'Occupation:'+ person['occupation'] except KeyError: #是捕获键值不存在时 pass >>> describePerson({'name':'Throatwobbler','age':42}) Description of Throatwobbler Age: 42 >>>
注:这里在打印职业时,使用加号而不是逗号。否则字符串'Occupaton:'在异常引发之前就会被输出。
查看某对象是否有write属性
try: object.write except AttributeError: print 'The object is not writeable' else: print 'The object is writeable'
相关文章推荐
- python学习六:异常处理、map/reduce/filter内置函数、python集合(set)类型、元组转列表
- python的错误类型和异常处理
- python3.4学习笔记(二) 类型判断,异常处理,终止程序
- python知识:json格式文本;异常处理;字符串处理;unicode类型和str类型转换
- Python异常处理和异常类型
- Python异常处理体系简介
- 编译提示“未处理的‘System.ArithmeticException’类型的异常出现在 system.drawing.dll”
- 书羊农历控件使用步骤及处理错误:引发了“System.Windows.Forms.AxHost.InvalidActiveXStateException”类型的异常
- 未处理的“System.StackOverflowException”类型的异常出现在 mscorlib.dll
- “System.OutOfMemoryException”类型的异常在 mscorlib.dll 中发生,但未在用户代码中进行处理
- 未处理的“System.FormatException”类型的异常出现在 mscorlib.dll 中
- 从GridView中直接导出数据到Excel文件 处理导出乱码 类型“GridView”的控件“XXXX”必须放在具有 runat=server 的窗体标记内。”的异常
- 转:Python异常处理
- 处理[未处理的“System.StackOverflowException”类型的异常出现在 System.Windows.Form.dll]异常
- “System.StackOverflowException”类型的未经处理的异常出现在 mscorlib.dll 中。
- 在用c++读取xml文件时,运行时出现以下错误:出现未处理的“System.Xml.XmlException”类型的异常出现在 system.xml.dll 中
- 未处理的“System.ComponentModel.Win32Exception”类型的异常出现在 System.dll 中 解决一法
- progressive类型的jpeg在嵌入系统中的异常处理
- Python入门的36个例子 之 33 -> try – 异常是不可避免的,关键是怎样处理
- python笔记(十) - 异常和文件处理