Python中两种处理错误方法的比较

我所说的处理错误的方法,其实是try:,exceptraise这两种。

首先抛出一个实例,

dictt={'a':1,'b':2,'c':3}
try:
if dictt['d']>1: #字典中没有'd'
print("right!")
except KeyError:
print("there is no 'd'")

该程序的运行结果:

  there is no 'd'

而改为raise时,执行结果却是:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhgAAAA0CAIAAABHF9YjAAAGYUlEQVR4nO2c25LjKgxF8/8/7fM0OW6DxJYEvmWtmprqxkISGNg2JP3ZfoHP5+oMoAZ3EODG/Jufn8+ff6ui1ZznqrMGRekOA31sLBpF3EeAu7ITksP/qwLWnF8uJDdczhal1HWrxyo+Mcx1CAAraZ46lwc8V0h+4bn4R4Sk6BMAluEKyXeD4rBT4W99+JbWBproc5+PuM3S9ZaIHtr9m951XYfRDUnxHn3Lux5Eug6LnSwmCQDnMnoj6c789ufzC8UVpJv8/v9QdD3utqbrhun5+YiBHLdpIZnSycgGwC0RhKRfr/eiYNmIK6Do08nKsu9WV5azyiOw80g+t+tymtoNN7SvNL8bKNTJCAnALUkJifh+MCxMvHNYmx4WFSFxPCRCW3Undl00n0P5aiFx7qzYyQgJwC2JC0l9f2ZKYW5F04VEFzwlbjTQipRCPi1vRQkXo4saDwD3oNlkaLcdupse3Y0Xx3KKz/2v+nvJofq3xE/eylMMPWxmtLBte5vtELHn/XsxjGVZ+oG6Tg4l3VgAcDW/MQ9Zbp4OdxDgxjA/AQCgBEICAAAl7i0k+yONuh9IQNedwLs7edYshhsTvLuH81L/OFQ5mB2GO7jVj3ytrCrJFNsSzdxxdQ6Jk3bR4SXVD64qLarfxL2rd1MREucGTe+3y4d33Yn+QZjZaaSmUChYul+c8RfyWUxgiqu2+iXLRzSolfA71r5Qi6YPhul+psRdsTrX3Z7QRTcZ3ufsvix4BK8JyQr7uT7nPl/8lJA4r5sIiVIlmsPJPOjj1D8iJKeNqAXrZ0FIujtOSiorXiEtb8Ntsf2vB4M2z72Z06KDQyuZofEwkFLYbZp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Mz+j75+Qw/aFtsMgAAbNt2FJL0kvqgtfhBqQIAPIG/X+/oXLf/ZuLh56/Boe7BubWHZn01pGuZ4577bwAAD6enEP9fjHxL3PKgfB/Q0okVKz4SAgAwFXdry/ka+SbITPurVegIyXQQEgCAqbgnz/55tW45LERIAAAeiywk/qtGSAkQEgCAFzH6Hol1NN21sU7mLeODQ90yDYftAACz+YHP+wIAwEqyX2IHAADYtu3Nf2sLAABO4T/OWFHCyvC1eAAAAABJRU5ErkJggg==" alt="" />

显然,由于‘f’是不存在的,所以if无法执行,导致raise也不能执行

两者(try:,except和raise)的区别:

前者,无论if中条件是什么,都可以运行,不报错;而后者,if中的条件要符合一定标准,不然raise运行不了。还有,raise会中断程序,显示红色的错误提示,而红色的提示正是raise中设定的。

总而言之,raise的使用一般具有实际意义。典型的用法:定义了一个接受多个参数的函数,而其中一个参数类型错误,此时用raise进行错误提示非常合适。

Example:

#实现两个整数的加法运算
def summ(add1,add2):
if (type(add1))==type(1) and (type(add2))==type(1):
return (add1+add2)
else:
raise TypeError("The two parameters should be integers")
上一篇:Java如何安装JDK,配置环境变量。超级详细图及操作


下一篇:[flask/python/web] 解析flask web开发(Miguel著)一书第11章主页不显示博文表单的问题