try…except
有时候我们写程序的时候,会出现一些错误或异常,导致程序终止。使用try…except,这样程序就不会因为异常而中断。把可能发生错误的语句放在try模块里,用except来处理异常。except可以处理一个专门的异常,也可以处理一组圆括号中的异常,如果except后没有指定异常,则默认处理所有的异常。每一个try,都必须至少有一个except。
a=10
b=0
try:
c=a/b
print(c)
exceptZeroDivisionErrorase:
print(e)
print("done")
运行:
divisionbyzero
done
可以看出在有异常的情况下,程序依然执行完毕。
2.try…except…else
try…except…else语句,当没有异常发生时,else中的语句将会被执行。
a=10
b=0
try:
c=b/a
print(c)
except(IOError,ZeroDivisionError)asx:
print(x)
else:
print("noerror")
print("done")
运行:
0.0
noerror
done
3.raise引发一个异常
raise是引发一个异常来检查某个条件是否成立。
inputValue=4.2
iftype(inputValue)!=type(1):
raiseValueError
else:
print(inputValue)
运行:
...
raiseValueError
ValueError
4.try…finally
无论异常是否发生,在程序结束前,finally中的语句都会被执行。
a=10
b=0
try:
print(a/b)
finally:
print("alwaysexcute")
运行:
alwaysexcute
Traceback(mostrecentcalllast):
...
print(a/b)
ZeroDivisionError:divisionbyzero
可以看出finally最终执行,异常也照常报错。
5.try…except…finally
a=10
b=0
try:
print(a/b)
except:
print("error")
finally:
print("alwaysexcute")
结果:
error
alwaysexcute
6.自定义一个异常类
自定义一个MyException类,继承Exception。
classMyException(Exception):
def__init__(self,message):
Exception.__init__(self)
self.message=message
a=9
ifa<10>
try:
raiseMyException("myexcepitionisraised")
exceptMyExceptionase:
print(e.message)
结果:
myexcepitionisraised
7.把异常保存到一个日志文件中,来分析这些异常:
importtraceback
try:
print('here1:',5/2)
print('here2:',10/5)
print('here3:',10/0)
exceptExceptionase:
f=open("log.txt",'a')
#traceback.print_exc(file=f)#打印输出到屏幕
traceback.print_exc(file=f)#输出到文件
f.flush()
f.close()
结果:
here1:2.5
here2:2.0
会生成一个log.txt的文件。
8.捕获异常的小方法
方法一:捕获所有异常
a=10
b=0
try:
print(a/b)
exceptExceptionase:
print(Exception,":",e)
finally:
print("alwaysexcute")
运行:
alwaysexcute
方法二:采用traceback模块查看异常
importtraceback
try:
print('here1:',5/2)
print('here2:',10/5)
print('here3:',10/0)
exceptExceptionase:
traceback.print_exc()
运行:
here1:2.5
here2:2.0
Traceback(mostrecentcalllast):
File"/Users/lilong/Desktop/online_release/try_except_use.py",line59,in
print('here3:',10/0)
ZeroDivisionError:divisionbyzero
方法三:采用sys模块回溯最后的异常
importsys
try:
print('here1:',5/2)
print('here2:',10/5)
print('here3:',10/0)
exceptExceptionase:
info=sys.exc_info()
print(info[0],":",info[1])
运行:
here1:2.5
here2:2.0
注意:万能异常Exception被检测的代码块抛出的异常有多种可能性,并且我们针对所有的异常类型都只用一种处理逻辑就可以了,那就使用Exception,除非要对每一特殊异常进行特殊处理。
9.python所有的标准异常类:
异常名称描述BaseException:所有异常的基类SystemExit:解释器请求退出KeyboardInterrupt:用户中断执行(通常是输入^C)Exception:常规错误的基类StopIteration:迭代器没有更多的值GeneratorExit:生成器(generator)发生异常来通知退出SystemExitPython:解释器请求退出StandardError:所有的内建标准异常的基类ArithmeticError:所有数值计算错误的基类FloatingPointError:浮点计算错误OverflowError:数值运算超出最大限制ZeroDivisionError:除(或取模)零(所有数据类型)AssertionError:断言语句失败AttributeError:对象没有这个属性EOFError:没有内建输入,到达EOF标记EnvironmentError:操作系统错误的基类IOError:输入/输出操作失败OSError:操作系统错误WindowsError:系统调用失败ImportError:导入模块/对象失败KeyboardInterrupt:用户中断执行(通常是输入^C)LookupError:无效数据查询的基类IndexError:序列中没有没有此索引(index)KeyError:映射中没有这个键MemoryError:内存溢出错误(对于Python解释器不是致命的)NameError:未声明/初始化对象(没有属性)UnboundLocalError:访问未初始化的本地变量ReferenceError:弱引用(Weakreference)试图访问已经垃圾回收了的对象RuntimeError:一般的运行时错误NotImplementedError:尚未实现的方法SyntaxErrorPython:语法错误IndentationError:缩进错误TabErrorTab:和空格混用SystemError:一般的解释器系统错误TypeError:对类型无效的操作ValueError:传入无效的参数UnicodeErrorUnicode:相关的错误UnicodeDecodeErrorUnicode:解码时的错误UnicodeEncodeErrorUnicode:编码时错误UnicodeTranslateErrorUnicode:转换时错误Warning:警告的基类DeprecationWarning:关于被弃用的特征的警告FutureWarning:关于构造将来语义会有改变的警告OverflowWarning:旧的关于自动提升为长整型(long)的警告PendingDeprecationWarning:关于特性将会被废弃的警告RuntimeWarning:可疑的运行时行为(runtimebehavior)的警告SyntaxWarning:可疑的语法的警告UserWarning:用户代码生成的警告
参考:https://www.cnblogs.com/Lival/p/6203111.html