python异常处理

try 后面写正常运行的程序代码,except即为异常情况

a = 0
b = 10
try:
    c = b / int(a)
    print(c)
except:
     print("error")

  

a = 0
b = 10
try:
    c = b / int(a)
    print(c)
except Exception as e:
    print('Exception')
    print(e)

 

  • try ....except...else 语句,当没有异常发生时,else中的语句将会被执行;发生异常时,else的语句没有被运行
  • 当执行try ...finally 语句时,无论异常是否发生,在程序结束前,finally中的语句都会被执行。
a = input("a=")# 输入:0或-
b = 10
try:
    c = b / int(a)
    print(c)
except ZeroDivisionError as e:
    print('ZeroDivisionError')
    print(e)
except ValueError as e:
    print('ValueError')
    print(e)
except Exception as e:
    print('Exception')
    print(e)
else:#不出现异常,就执行本语句
    print("else")
finally:#不管是否有异常,都会执行本句
    print('finally')

  

raise引发一个异常,比如,当一个条件不满足用户意愿时引发一个异常

a=3
if a<4:
    raise Exception
else: print(a)

 

 

参考: 

https://edu.hellobi.com/course/234/play/lesson/3977

https://www.cnblogs.com/bokeyuan11/p/9146607.html

posted @ 2020-10-30 18:19  耐烦不急  阅读(114)  评论(0编辑  收藏  举报