捕捉异常可以使用try/except语句实现
创建一个让用户输入两个数,然后进行相除的程序:
x = input('Enter the first number: ')y = input('Enter the second number: ')print x/y
如果用户输入0作为第二个数,结果如下:
Traceback (most recent call last): file "C:/Users/�1�7�1�7�1�7�1�7/PycharmProjects/unTitled2/3.py", line 3, in <module> print x/yZerodivisionError: integer division or modulo by zero
为了捕捉异常并且做出错误处理,应该如下书写:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/yexcept ZerodivisionError: print "The secon number can't be zero!"
输出结果:
Enter the first number: 1Enter the second number: 0The secon number can't be zero!
以上是内存溢出为你收集整理的Python基础教程第8章 8.3 捕捉异常全部内容,希望文章能够帮你解决Python基础教程第8章 8.3 捕捉异常所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)