Syntax Error v.s. Exception, (try, except, finally) - Python

Syntax Error VS. Exception

Syntax Error 是语法错误,有可能是出现了typo比如request写成了reqeust,或者python 2,3的不兼容导致, 比如在Py3里写print i(print (i) 在python3里需要加括号。)

Exception 以下代码简单举例

number = int(input('Enter a number please: \n'))
print(720/number)

运行后,输‘asasasa’,” , 0.2 等都会出现exception或valueError (PyCharm会抛出valueError), 这是因为输入的type非int;而输入0 则会出现ZeroDivisionError,因为实际情况下0不可以作为分子。
解决如上exception,可以通过下述简单代码来处理:

while True:
    try:
        number = int(input('Enter a number please: \n'))
        print(7/number)
        break

    # this exception helps when you get a ValueError
    except ValueError:
        print('Please make sure you enter an integer. \n')

    # this exception gives a prompt when the number user types is zero
    except ZeroDivisionError:
        print('Please make sure you enter an integer that\'s not a zero. \n')

    #'except' is used as a general exception when you're not sure about the source of your problem, not recommended
    except:
        print('Please enter an integer. \n')

    #finally executes no matter what
    finally:
        print('this step is complete' )

运行上面一段代码,输入不同类型参数后得到以下输出:
这里写图片描述

至此,针对这段代码的exception就处理结束了。
如代码内注释提到的,except: 是作为一个general的exception处理,并不推荐使用,而finally: 是在任何条件下都会执行的语句。

注:本文只针对一些error和exception举例,并非涵盖所有
若有其他疑问,欢迎探讨,或Google,或stackoverflow。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值