Python 基础知识之 异常处理

异常处理

  • 程序中有可能会出现异常或错误,导致程序终止,使用异常处理,能捕捉到操作信息,方便定位异常位置,通过对异常的预处理可避免程序的崩溃

处理方法

  • try except

    a=10
    b=0
    c=a/b
    print "done

    会抛出异常

    a=10
    b=0
    try:
    c=a/b
    print c
    except ZeroDivisionError,e:
    print e.message
    print "done"

    运行结果:
    integer division or modulo by zero
    done
    捕捉到了异常,并阻止了程序的崩溃
  • try except else:当没有异常发生时, else 中的语句会被执行

    a=10
    b=0
    try:
    c = b/ a
    print c
    except (IOError ,ZeroDivisionError),x:
    print x
    else:
    print "no error"
    print "done"

    运行结果:
    0
    no error
    done
  • raise 引发一个异常

    inputValue=input("please input a int data :")
    if type(inputValue)!=type(1):
        raise ValueError
    else:
        print inputValue

    假设输入1.2,运行结果为:
    please input a int data :1.2
    Traceback (most recent call last):
    File “C:/Users/lirong/PycharmProjects/untitled/openfile.py”, line 3, in
    raise ValueError
    ValueError

  • try finally:无论异常是否发生,finally 中的语句都会被执行

    a=10
    b=0
    try:
        print a/b
    finally:
        print "always excute"

    运行结果:
    Traceback (most recent call last):
    always excute
    File “C:/Users/lirong/PycharmProjects/untitled/openfile.py”, line 4, in
    print a/b
    ZeroDivisionError: integer division or modulo by zero

    finally 也可以和 except 配合使用

    a=10
    b=0
    try:
        print a/b
    except:
        print "error"
    finally:
        print "always excute"

    运行结果:
    error
    always excute

自定义异常类,集成 Exception

```
class MyException(Exception):
    def __init__(self,message):
        Exception.__init__(self)
        self.message=message   
a=input("please input a num:")
if a<10:
    try:
        raise MyException("my excepition is raised ")
    except MyException,e:
        print e.message
```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值