Python notes (xv) _ Exception Handling

try-except statement

try:

Code is detected

except Exception [as reason]:

After an exception handling code

 

Example:

>>>try:

sum = 1+'1'

f = open ( 'undefined file .txt')

print(f.read())

f.close

except OSError as reason:

print ( 'file error it wrong reasons:!' + str (reason))

except TypeError as reason:

print ( 'type error' + str (reason))

Run Results: Type Error unsupported operand type (s) for +: 'int' and 'str'

Wherein the third row to the seventh row code is not running, because once the abnormal try statement, it will directly positioned to the corresponding sentence except to the rest of the detection code will not be executed

 

try-finally statement

try:

Code is detected

except Exception [as reason]:

After an exception handling code

finally:

Anyway the code to be executed

 

Example:

try:

f=open('123.txt','w')

print(f.write('hello'))

sum = 1 + '1' # exception occurs here skip f.close () statements, resulting in data writing can not be stored

f.close()

except (OSError,TypeError):

print ( 'it wrong!')

 

So you can use try-finally statement to avoid this situation, change:

try:

f=open('123.txt','w')

print(f.write('hello'))

sum = 1 + '1' # exception occurs here skip f.close () statements, resulting in data writing can not be stored

f.close()

except (OSError,TypeError):

print ( 'it wrong!')

finally:

f.close()

 

raise statement

Itself an exception is thrown

>>>try:

for each in range(3):

if each==1:

raise KeyboardInterrupt

print(each)

except KeyboardInterrupt:

print ( 'Quit it!')

0

Quit it

 

 

 

python standard exceptions summary

 

AssertionError

Assertion (assert) failure

AttributeError

尝试访问未知的对象属性

EOFError

用户输入文件末尾标志EOF(Ctrl+d)

FloatingPointError

浮点计算错误

GeneratorExit

generator.close()方法被调用的时候

ImportError

导入模块失败的时候

IndexError

索引超出序列的范围

KeyError

字典中查找一个不存在的关键字

KeyboardInterrupt

用户输入中断键(Ctrl+c)

MemoryError

内存溢出(可通过删除对象释放内存)

NameError

尝试访问一个不存在的变量

NotImplementedError

尚未实现的方法

OSError

操作系统产生的异常(例如打开一个不存在的文件)

OverflowError

数值运算超出最大限制

ReferenceError

弱引用(weak reference)试图访问一个已经被垃圾回收机制回收了的对象

RuntimeError

一般的运行时错误

StopIteration

迭代器没有更多的值

SyntaxError

Python的语法错误

IndentationError

缩进错误

TabError

Tab和空格混合使用

SystemError

Python编译器系统错误

SystemExit

Python编译器进程被关闭

TypeError

不同类型间的无效操作

UnboundLocalError

访问一个未初始化的本地变量(NameError的子类)

UnicodeError

Unicode相关的错误(ValueError的子类)

UnicodeEncodeError

Unicode编码时的错误(UnicodeError的子类)

UnicodeDecodeError

Unicode解码时的错误(UnicodeError的子类)

UnicodeTranslateError

Unicode转换时的错误(UnicodeError的子类)

ValueError

传入无效的参数

ZeroDivisionError

除数为零

Guess you like

Origin www.cnblogs.com/demilisi/p/11038389.html