全文共1983字,预计学习时长5分钟

图源:unsplash

写代码必然会出现错误,而错误处理可以针对这些错误提前做好准备。通常出现错误时,脚本会停止运行,而有了错误处理,脚本就可以继续运行。为此,我们需要了解下面三个关键词:

·        try:这是要运行的代码块,可能会产生错误。

·        except:如果在try块中出现错误,将执行这段代码。

·        finally:不管出现什么错误,都要执行这段代码。

现在,我们定义一个函数“summation”,将两个数字相加。该函数运行正常。

>>> defsummation(num1,num2):        print(num1+num2)>>>summation(2,3)5

接下来,我们让用户输入其中一个数字,并运行该函数。

>>> num1 = 2>>> num2 = input("Enter number: ")Enter number: 3>>> summation(num1,num2)>>> print("Thisline will not be printed because of the error")---------------------------------------------------------------------------TypeError                                Traceback (most recent call last)<ipython-input-6-2cc0289b921e> in <module>----> 1 summation(num1,num2)      2 print("This line will notbe printed because of the error")
<ipython-input-1-970d26ae8592> in summation(num1, num2)      1 def summation(num1,num2):----> 2     print(num1+num2)
TypeError: unsupported operand type(s) for +:  int  and  str

“TypeError”错误出现了,因为我们试图将数字和字符串相加。请注意,错误出现后,后面的代码便不再执行。所以我们要用到上面提到的关键词,确保即使出错,脚本依旧运行。

>>> try:        summed = 2 +  3     except:        print("Summation is not ofthe same type")Summation is not of the same type

可以看到,try块出现错误,except块的代码开始运行,并打印语句。接下来加入“else”块,来应对没有错误出现的情况。

>>> try:        summed = 2 + 3    except:        print("Summation is not ofthe same type")    else:        print("There was no errorand result is: ",summed)There was no error and result is:  5

接下来我们用另外一个例子理解。这个例子中,在except块我们还标明了错误类型。如果没有标明错误类型,出现一切异常都会执行except块。

>>> try:        f = open( test , w )        f.write("This is a testfile")    except TypeError:        print("There is a typeerror")    except OSError:        print("There is an OSerror")    finally:        print("This will print evenif no error")This will print even if no error

现在,故意创造一个错误,看看except块是否与finally块共同工作吧!

>>> try:        f = open( test , r )        f.write("This is a testfile")    except TypeError:        print("There is a typeerror")    except OSError:        print("There is an OSerror")    finally:        print("This will print evenif no error")There is an OS errorThis will print even if no error

推荐阅读专题

留言点赞发个朋友圈

我们一起分享AI学习与发展的干货

编译组:李紫瑶、邓逸瑶

相关链接:

https://levelup.gitconnected.com/errors-and-exception-handling-in-python-e3560a879119

如转载,请后台留言,遵守转载规范

推荐文章阅读

ACL2018论文集50篇解读

EMNLP2017论文集28篇论文解读

2018年AI三大顶会中国学术成果全链接

ACL2017论文集:34篇解读干货全在这里

10篇AAAI2017经典论文回顾

长按识别二维码可添加关注

读芯君爱你

Python报错不要慌,这三个关键词帮你解决问题!相关推荐

  1. python 报错继续执行_Python报错不要慌,这三个关键词帮你解决问题!

    本文转载自公众号"读芯术"(ID:AI_Discovery). 写代码必然会出现错误,而错误处理可以针对这些错误提前做好准备.通常出现错误时,脚本会停止运行,而有了错误处理,脚本就 ...

  2. 已安装Anaconda情况下,命令行pip,python报错(详细 已解决)

    已安装Anaconda情况下,命令行pip,python报错(已解决) 这是报错截图 解决方案如下: 1.首先可以去找到anaconda文件夹,并打开该文件目录下的Script文件夹,查看是否有pip ...

  3. python报错TypeError: must be str, not int

    python报错TypeError: must be str, not int 字符串拼接一个整型变量报错,代码如下 for i in range(1,586):res = 'test' + i 报错 ...

  4. 遇到代码不生效或者报错不要慌

    以轮播图为例: 当遇到控制台报错 这种情况就需要看控制台报的错误是什么. 比如上面这种就是说变量i未定义,直接使用,网页就会报错. 当控制台没有报错,轮播图没有实现自动播放的功能 这时候需要检查自己那 ...

  5. python 报错汇总-- pip install pycrypto

    python 报错汇总-- pip install pycrypto 很多新手和老鸟在安装pycrypto时候会报各种错, 废话不多说,直接上: 原因 我也报了文末的错说是VC14什么的,花了差不多三 ...

  6. python 报错 IndentationError: expected an indented block SyntaxError: invalid character in identifie

    红色方框那里敲击一个空格就好! 输入要在全英情况下! 另外,还要注意括号的事情.括号别出错误! IndentationError: expected an indented block的报错: Syn ...

  7. Python安装库较慢问题,Python报错pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool解决方法

    本文参考:https://blog.csdn.net/sinat_26811377/article/details/99698807 出现问题 在安装第三方库的时候,Python报错pip._vend ...

  8. 解决Python报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 658: illegal multibyte

    解决Python报错–UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 658: illegal multibyte ...

  9. python报错UnicodeDecodeError: ‘ascii‘ codec can‘t decode byte 0xe8 in position 0 解决方案

    python报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0 解决方案 参考文章: (1)python报 ...

最新文章

  1. 参加Java培训需要注意什么
  2. Canonical面向Ubuntu 16.04 LTS发布首批内核安全修复补丁
  3. docker搭建pwn环境
  4. leetcode 384. Shuffle an Array | 384. 打乱数组(Fisher-Yates洗牌算法)
  5. 命令行运行jmeter脚本
  6. python封装exe 时间time问题_python模块之datetime
  7. 某位程序猿柬埔寨开发offer到手,薪资翻倍,去吗?网友:面向阎王编程...
  8. 《Python游戏趣味编程》 第10章 拼图游戏
  9. OpenResty(nginx)操作mysql的初步应用
  10. useradd - 帐 号 建 立 或 更 新 新 使 用 者 的 资 讯
  11. Windows XP英文版安装中文语言包来解决无法显示中文的方法(转载)
  12. AUTOCAD——标注打断
  13. 复盘:图像饱和度计算公式和图像信噪(PSNR)比计算公式
  14. 51单片机智能小车——超声波
  15. 软件著作权的申请超详细图文
  16. eclipse php jquery,Eclipse 支持jQuery 自动提示
  17. 基于Springboot拦截器的AES报文解密
  18. 【Monkey Run】Excel编程 VBA
  19. 绕过知乎网页版禁止转载限制进行复制
  20. 9大常见光固化3D打印树脂分析

热门文章

  1. 作为使用者如何应对JCenter远程仓库停止维护
  2. http://pan.baidu.com/share/link?shareid=2725301264uk=3138325909
  3. 计算机课教学常规要求,职业学校计算机专业常规课堂教学模式探究
  4. linux无线鼠标右键自动选择,2020年高性价比无线鼠标推荐
  5. android dss 流媒体开发,DSS流媒体服务器搭建
  6. jsp获取静态服务器文件路径,11、统一处理异常、处理静态资源访问、项目中的绝对地址跟相对地址问题...
  7. 基于ndis protocol driver 后门 分析
  8. PostgreSQL11 MYSQL_安装postgresql11.5
  9. 下列有关预防计算机病毒的做法或想法,Windows7试题
  10. 深入理解Docker原理