day21异常处理

程序员在写代码的时候难免会出现错误,错误可以分两种;一种是语法错;另一种是逻辑错误。

在python中不同的异常可以用不同的类型去标识。

AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的

常用异常
常用异常
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
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
ZeroDivisionError

更多异常
更多异常

既然出现了错误,就要想办法去解决:

异常发生以后后面的代码就不执行了,导致代码运行崩溃。

一、可以用if判断式

1、if判断式的异常处理只能针对某一段代码,对于不同的代码段的相同类型的错误需要写重复的if来进行处理。

2、在你的程序中频繁的写与程序本身无关,与异常处理有关的if,会使得代码可读性差

3、if是可以解决异常的,但是不能定论if不能作为异常处理的。

二、python为每一种异常定制了一个类型,然后提供了一种特定的语法结构用来进行异常处理

try:
    被检测的代码块
expect 异常类型:
    try一旦检测到异常就执行这个位置代码

万能异常 :Exception,它能捕获任意异常

s1 = 'hello'
try:
    int(s1)
except Exception as e:
    print(e)

无论出现什么异常,统一丢给他就够了

 

如果想要的效果是,对于不同的异常我们需要定制不同处理逻辑,拿就需要用到多支。

s1 = "hello"
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
expect ValueError as e:
    print(e)
s1 = "hello"
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
except Exception as e:
    print(e)

异常的其他机构:

s1 ="hello"
try :
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
else:
    print("若没有异常执行此处")
finally:
    print("无论异常与否,都会执行该模块")

主动触发

try:
    raise TypeError("类型错误")
except Exception as e:
    print(e)

断言

assert  1== 1


assert 1 ==2

try..except的方式比较if的方式的好处

try..except这种异常处理机制就是取代if那种方式,让你的程序在不牺牲可读性的前提下增强健壮性和容错性

异常处理中为每一个异常定制了异常类型(python中统一了类与类型,类型即类),对于同一种异常,一个except就可以捕捉到,可以同时处理多段代码的异常(无需‘写多个if判断式’)减少了代码,增强了可读性 

 

使用try..except的方式

1:把错误处理和真正的工作分开来
2:代码更易组织,更清晰,复杂的工作任务更容易实现;
3:毫无疑问,更安全了,不至于由于一些小的疏忽而使程序意外崩溃了;

posted @ 2017-09-13 15:08  hello沃德  阅读(58)  评论(0)    收藏  举报