异常处理

#!/bin/env python
# -*- coding: UTF-8 -*-

#主动诱发异常  raise Exception('我创建的异常')

#raise Exception('我创建的异常')

#自定义异常
class SomeCustomException(Exception):
    pass

#扑捉异常
try:
    x = input('Enter the first number:')
    y = input('Enter the second number:')
    print x/y
except ZeroDivisionError:
    print "--------Y不能为0."
except NameError:
     print "--------Y必须是数字."

#也可以使用except (NameError,TypeError):无论触发哪个异常都打印一个信息
try:
    x = input('Enter the first number:')
    y = input('Enter the second number:')
    print x/y
except (NameError,TypeError),e:
    print e

#使用else退出异常死循环
#这里的循环只在没有异常引发的情况下才会退出(由异常里的else执行)
#换句话说只要错误发生,程序会不对的要求重新输入。
while True:
    try:
        x = input('Enter the first number:')
        y = input('Enter the second number:')
        print x/y
    except (NameError,TypeError),e:
        print e
    else:
        break




posted @ 2020-08-26 21:00  名字很长容易被惦记  阅读(136)  评论(0编辑  收藏  举报