代码:
try:
print open("Demo.py", 'r')
n = 1 / 0
except ZeroDivisionError, e:
print "zeroDivisionError", e
except ValueError, e:
print "ValueError", e
else:
print "No Error catched"
finally:
print "finally" finally是无论有无错误都会执行。
Build-in Exception的种类
Python(2.x)内置Exception的继承关系见下图:
The class hierarchy for built-in exceptions is: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StandardError | +-- BufferError | +-- ArithmeticError | | +-- FloatingPointError | | +-- OverflowError | | +-- ZeroDivisionError | +-- AssertionError | +-- AttributeError | +-- EnvironmentError | | +-- IOError | | +-- OSError | | +-- WindowsError (Windows) | | +-- VMSError (VMS) | +-- EOFError | +-- ImportError | +-- LookupError | | +-- IndexError | | +-- KeyError | +-- MemoryError | +-- NameError | | +-- UnboundLocalError | +-- ReferenceError | +-- RuntimeError | | +-- NotImplementedError | +-- SyntaxError | | +-- IndentationError | | +-- TabError | +-- SystemError | +-- TypeError | +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning
抛出自定义Exception使用以下语法:
raise MyException("this is my Exception") 在测试代码中,我们对Exception的处理中可以直接print exception。但是实际生产代码中直接打印log可能不是很妥。我们可以通过简单的配置使用logging.exception(msg)将错误打印到日志中。如何正确使用python内置的logging模块,可以另开一篇文章介绍。
以上就是python学习笔记-错误处理的内容,更多相关内容请关注PHP中文网(HdhCmsTestgxlcms测试数据)!
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did86226