Python-Errors and Exceptions(未完待续)


到目前为止,错误消息还没有被提到,但是如果您尝试过这些示例,您可能已经看到了一些。(至少)有两种可区分的错误:语法错误和异常。

1.语法错误

语法错误,也称为解析错误,可能是你在学习Python时最常见的问题:

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

由于过于常见,那么就不考虑了。

2.异常

即使是陈述、表达式都语法正确,它也会造成一种错误,当你要取执行它。当执行的时候发生的错误称为异常。例如:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
# 发生了除以0异常
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
# 发生了名字异常 spam没有被定义
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
# 不能把int对象隐式转化为str

以一种栈回溯的方式。

操纵异常

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

try 是按如下工作的:

  • 首先,try 到except之间的代码被执行。
  • 如果没有异常发生,except的代码被跳过,try 语句完成。
  • 如果异常发生,执行except,然后继续执行。
  • 如果异常没有匹配,那么将它往外抛,如果没有控制器捕获到相应的异常,那么发生了一个未处理的异常,然后执行停止,显示一系列信息。
class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

得BCD

for cls in [B, C, D]:
    try:
        raise cls()
    except B:
        print("B")
    except C:
        print("C")
    except D:
        print("D")
        

得BBB,按照顺序。
派生类可以匹配父类。

最后一个except子句可以省略异常名,作为通配符。要非常谨慎地使用它,因为用这种方法很容易掩盖真正的编程错误!它还可以用来打印错误消息,然后重新引发异常(允许调用者处理异常):

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
  • 处理OSError
  • 处理ValueError
  • 处理其他:raise抛出。
for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

else子句的使用比向try子句添加额外的代码要好,因为它避免了意外捕获一个异常,该异常不是由try…except语句保护的代码引发的。
当异常发生时,它可能有一个关联的值,也称为异常的参数。参数的存在和类型取决于异常类型。
except子句可以在异常名称后面指定一个变量。该变量绑定到一个异常实例,该实例的参数存储在instance.args中。为了方便起见,exception实例定义了_str__(),因此可以直接打印参数,而不需要引用.args。也可以在引发异常之前先实例化异常,然后根据需要向异常添加任何属性。

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

如果异常有参数,则将它们打印为未处理异常消息的最后一部分(“detail”)。
异常处理程序不仅处理在try子句中立即发生的异常,而且还处理在try子句中调用(甚至是间接调用)的函数中发生的异常。例如:

>>> def this_fails():
...     x = 1/0
...
>>> try:
...     this_fails()
... except ZeroDivisionError as err:
...     print('Handling run-time error:', err)
...
Handling run-time error: division by zero

4.抛出异常

raise语句允许程序员强制执行指定的异常。例如:

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

惟一要引发的参数表示要引发的异常。这必须是异常实例或异常类(从异常派生的类)。如果传递了异常类,它将隐式实例化,方法是调用它的构造函数而不带参数:

raise ValueError  # shorthand for 'raise ValueError()'

抛出异常 调用构造函数

Try中抛出的异常,在except如果找到对应的,那就会进行处理。

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...

5.用户-定义的异常

程序可以通过创建一个新的异常类来命名它们自己的异常。
异常类可以定义为任何其他类都可以做的任何事情,但通常保持简单,通常只提供一些属性,允许异常处理程序提取有关错误的信息。当创建一个可能产生几个不同错误的模块时,通常的做法是为该模块定义的异常创建一个基类,以及为不同错误条件创建特定异常类的子类:

# Exception->Error
class Error(Exception):
    """Base class for exceptions in this module."""
    pass

class InputError(Error):
    """Exception raised for errors in the input.

    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """

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

class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.

    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """

    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message

大多数异常都是用以“Error”结尾的名称定义的,类似于标准异常的命名。
许多标准模块定义它们自己的异常,以报告在它们定义的函数中可能发生的错误。更多关于类的信息在章节类中给出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值