python----异常处理

1、异常处理的执行顺序

try:
    statement1
except Exception as error:
    statement2
else:
    statement3
finally:
    statement4
raise Exception:

 

2、常见异常

  IndentationError: expected an indented block   缩进错误

  NameError: name 'continu' is not defined  输错了,如break写成了brea

  ValueError: invalid literal for int() with base 10: 'a'  值错误,数据类型的错误

  ZeroDivisionError: float division by zero 除0错误

 

3、举个例子,代码顺序执行,当发生异常时,改变代码的执行顺序

try:
    data1 = float(input("请输入除数"))
    data2 = float(input("请输入被除数"))
    print("{0} / {1} = {2}".format(data1,data2,data1/data2))
except ValueError as error:
    print(error)
except ZeroDivisionError as error:  //except Exception as error,Exception包括了python的大部分异常
    print(error)
finally:
    print("这里总会被执行到")

 

4、主动抛出异常

raise Exception("这是我主动抛出的异常")
控制台:
Traceback (most recent call last):
  File "D:/script/kecheng/lesson3/function.py", line 15, in <module>
    raise Exception("这是我主动抛出的异常")
Exception: 这是我主动抛出的异常
try:
    raise Exception("这是我主动抛出的异常")
except Exception as error:
    print(error)

 

posted @ 2019-10-25 13:48  红枣枸杞  阅读(165)  评论(0编辑  收藏  举报