异常(错误)也是对象哦

探讨python3中异常(错误)捕获
as 关键字的作用:a as b 意思是将a对象重命名为b


# raise 用于生成一个错误
# raise SomeError("SomeError will be raised")

# 错误的捕获
def funny_division1(anumber):
    try:
        # try语句用于放置任何可能引起错误的语句
        return 100/anumber
    except ZeroDivisionError:
        # except对捕获的错误进行的处理
        return "Silly wabbit, you can't divide by zero"
print(funny_division1(0))
print(funny_division1(50.0))
print(funny_division1("hello"))

# 通过叠加except语句,捕获不同的异常进行不同的处理
def funny_division3(anumber):
    try:
        if anumber == 13:
            raise ValueError("13 is an unluckly number")
        return 100/anumber
    except ZeroDivisionError:
        return "Enter a number other than zero"
    except TypeError:
        return "Enter a numerial value"
    except ValueError:
        print("No, No, not 13")
        raise ValueError

funny_division3(13)
funny_division3(0)
funny_division3("hello")

# 如果要对可能发生的几个不同的异常进行相同的处理
# 可以在except后添加括号,并在括号里面写入可能引发的异常
def funny_division2(anumber):
    try:
        if anumber == 13:
            raise ValueError("13 is an unluckly number")
        return 100/anumber
    except (ZeroDivisionError, TypeError):
        return "Enter a number other than zero"

for val in (0, "hello", 50.0, 13):
    print("Testing {}:".format(val), end=" ")
    print(funny_division2(val))

# 错误的args参数是错误的参数
def text(num):
    try:
        if not isinstance(num, str):
            raise TypeError("类型错了")
    except TypeError as e:
        print(e.args)

text(1)

# 下面两个关键字是在错误捕获中,else关键字只有没有错误发生时才会执行
# finally关键字一定在最后会执行的呀,即使在某个语句中有return关键字返回
# finally关键字内容仍然会执行

import random
some_exceptions = [ValueError, TypeError, IndexError, None]

try:
    choice = random.choice(some_exceptions)
    if choice:
        raise choice("An error")
except ValueError:
    print("Caught a ValueError")
except TypeError:
    print("Caught a TypeError")
except Exception as e:
    print("Caught some other error %s" % (e.__class__.__name__))
else:
    print("This code called if there is no exception")
finally:
    print("This cleanup code is always called")

猜你喜欢

转载自blog.csdn.net/killeri/article/details/81394851