2018-09-06-python-exception

本文介绍了Python中的异常处理机制,包括常见的语法错误、类型错误等异常示例,以及如何使用try...except...语句来捕获和处理异常。此外,还介绍了如何自定义异常类以应对特定的错误情况。
titlecategorylayouttagsdate
python中的exception
python
post
python
2018-09-06 00:00:24

Exception

在python中运行如下代码将会报错:

while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax

而正确的代码应该是:

while True:
    print('Hello world')
        while True:
            print('Hello world')

这是因为python解释器会对程序的错误抛出异常。类似的错误还有:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero


>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined


>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

处理Exception

像其他语言一样,我们可以使用try...except...关键字对这些异常进行捕获并进行处理:

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")

或者一次性处理多个异常,并忽略:

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except (RuntimeError, TypeError, NameError):
        pass

自定义Exception

我们可以自己定义一个异常,这样针对自定义的错误抛出异常。

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: HiThere

还可以自定义一个异常类:

class InputError(Error):
    """针对输入异常的自定义异常类

    Attributes:
        expression -- 哪一段代码异常
        message -- 异常的说明
    """

    def __init__(self, expression, message):
        self.expression = expression
        self.message = message

自定义异常之后,在编写代码的过程中可以自定义异常,比如:

raise InputError

对Exception处理后的终极操作

    try:
        raise KeyboardInterrupt
    finally:
        print('Goodbye, world!')

finally是对异常处理之后的清扫工作,指的是处理完异常之后还要进行的操作,比如上报异常、记录异常、日志等工作。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值