Python基础之:Python中的异常和错误

简介: Python基础之:Python中的异常和错误

目录



简介


和其他的语言一样,Python中也有异常和错误。在 Python 中,所有异常都是 BaseException 的类的实例。 今天我们来详细看一下Python中的异常和对他们的处理方式。


Python中的内置异常类


Python中所有异常类都来自BaseException,它是所有内置异常的基类。


虽然它是所有异常类的基类,但是对于用户自定义的类来说,并不推荐直接继承BaseException,而是继承Exception.


先看下Python中异常类的结构关系:


BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning


其中BaseException,Exception,ArithmeticError,BufferError,LookupError 主要被作为其他异常的基类。


语法错误


在Python中,对于异常和错误通常可以分为两类,第一类是语法错误,又称解析错误。

也就是代码还没有开始运行,就发生的错误。


其产生的原因就是编写的代码不符合Python的语言规范:


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


上面代码原因是 print 前面少了 冒号。


异常


即使我们的程序符合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


异常处理


程序发生了异常之后该怎么处理呢?


我们可以使用try except 语句来捕获特定的异常。


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


上面代码的执行流程是,首先执行try中的子语句,如果没有异常发生,那么就会跳过except,并完成try语句的执行。


如果try中的子语句中发生了异常,那么将会跳过try子句中的后面部分,进行except的异常匹配。如果匹配成功的话,就会去执行except中的子语句。


如果发生的异常和 except 子句中指定的异常不匹配,则将其传递到外部的 try语句中。

一个try中可以有多个except 子句,我们可以这样写:


try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")


一个except也可以带多个异常:


... except (RuntimeError, TypeError, NameError):
...     pass


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


try ... except语句有一个可选的 else 子句,在使用时必须放在所有的 except 子句后面。对于在 try 子句不引发异常时必须执行的代码来说很有用。 例如:


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()


except可以指定异常变量的名字 instance ,这个变量代表这个异常实例。


我们可以通过instance.args来输出异常的参数。


同时,因为异常实例定义了 __str__(),所以可以直接使用print来输出异常的参数。而不需要使用 .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


上面的例子中,我们在try字句中抛出了一个异常,并且指定了2个参数。


抛出异常


我们可以使用raise语句来抛出异常。


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


raise的参数是一个异常,这个异常可以是异常实例或者是一个异常类。


注意,这个异常类必须是Exception的子类。


如果传递的是一个异常类,那么将会调用无参构造函数来隐式实例化:


raise ValueError  # shorthand for 'raise ValueError()'


如果我们捕获了某些异常,但是又不想去处理,那么可以在except语句中使用raise,重新抛出异常。


>>> try:
...     raise NameError('HiThere')
... except NameError:
...     print('An exception flew by!')
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: HiThere


异常链


如果我们通过except捕获一个异常A之后,可以通过raise语句再次抛出一个不同的异常类型B。


那么我们看到的这个异常信息就是B的信息。但是我们并不知道这个异常B是从哪里来的,这时候,我们就可以用到异常链。


异常链就是抛出异常的时候,使用raise from语句:


>>> def func():
...     raise IOError
...
>>> try:
...     func()
... except IOError as exc:
...     raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in func
OSError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database


上面的例子中,我们在捕获IOError之后,又抛出了RuntimeError,通过使用异常链,我们很清晰的看出这两个异常之间的关系。


默认情况下,如果异常是从except 或者 finally 中抛出的话,会自动带上异常链信息。


如果你不想带上异常链,那么可以 from None 。


try:
    open('database.sqlite')
except IOError:
    raise RuntimeError from None
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError


自定义异常


用户可以继承 Exception 来实现自定义的异常,我们看一些自定义异常的例子:


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


finally


try语句可以跟着一个finally语句来实现一些收尾操作。


>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>


finally 子句将作为 try 语句结束前的最后一项任务被执行, 无论try中是否产生异常,finally语句中的代码都会被执行。


如果 finally 子句中包含一个 return 语句,则返回值将来自 finally 子句的某个 return 语句的返回值,而非来自 try 子句的 return 语句的返回值。


>>> def bool_return():
...     try:
...         return True
...     finally:
...         return False
...
>>> bool_return()
False
相关文章
|
运维 监控 算法
时间序列异常检测:MSET-SPRT组合方法的原理和Python代码实现
MSET-SPRT是一种结合多元状态估计技术(MSET)与序贯概率比检验(SPRT)的混合框架,专为高维度、强关联数据流的异常检测设计。MSET通过历史数据建模估计系统预期状态,SPRT基于统计推断判定偏差显著性,二者协同实现精准高效的异常识别。本文以Python为例,展示其在模拟数据中的应用,证明其在工业监控、设备健康管理及网络安全等领域的可靠性与有效性。
1585 13
时间序列异常检测:MSET-SPRT组合方法的原理和Python代码实现
|
人工智能 C# Python
处理python异常
本文介绍了Python中的异常处理机制,并实现了一个简单的异常装饰器。通过`try/except`语句捕获异常,结合`finally`子句完成清理工作。为进一步优化代码结构,文章提出了使用装饰器处理异常的方法,避免函数中大量冗长的异常处理语句。通过类封装异常装饰器,多个函数可共享异常处理逻辑,提升代码简洁性和可维护性。总结强调了装饰器在异常处理中的优势,使代码更加优雅高效。
386 27
|
人工智能 Shell 开发工具
[oeasy]python065python报错怎么办_try_试着来_except_发现异常
本文介绍了Python中处理异常的基本方法,重点讲解了`try`和`except`的用法。通过一个计算苹果重量的小程序示例,展示了如何捕获用户输入错误并进行处理。主要内容包括: 1. **回顾上次内容**:简要回顾了Shell环境、Python3游乐场和Vim编辑器的使用。 2. **编写程序**:编写了一个简单的程序来计算苹果的总重量,但发现由于输入类型问题导致结果错误。 3. **调试与修正**:通过调试发现输入函数返回的是字符串类型,需要将其转换为整数类型才能正确计算。
595 32
如何处理python的常见异常问题
在Python语言中,python异常处理机制主要依赖try、except、else、finally和raise五个关键字。本篇文章将为大家详细讲解一下如何处理python的常见异常问题。
|
数据库 Python
[oeasy]python066_如何捕获多个异常_try_否则_else_exception
本文介绍了Python中`try...except...else`结构的使用方法。主要内容包括: 1. **回顾上次内容**:简要复习了`try`和`except`的基本用法,强调了异常处理的重要性。 2. **详细解释**: - `try`块用于尝试执行代码,一旦发现错误会立即终止并跳转到`except`块。 - `except`块用于捕获特定类型的异常,并进行相应的处理。 - `else`块在没有异常时执行,是可选的。 3. **示例代码**:通过具体例子展示了如何捕获不同类型的异常(如`ValueError`和`ZeroDivisionError`),并解释了异常处理
391 24
|
存储 索引 Python
Python生成器、装饰器、异常(2)
【10月更文挑战第16天】
388 1
Python生成器、装饰器、异常(2)
|
测试技术 开发者 Python
对于Python中的异常要如何处理,raise关键字你真的了解吗?一篇文章带你从头了解
`raise`关键字在Python中用于显式引发异常,允许开发者在检测到错误条件时中断程序流程,并通过异常处理机制(如try-except块)接管控制。`raise`后可跟异常类型、异常对象及错误信息,适用于验证输入、处理错误、自定义异常、重新引发异常及测试等场景。例如,`raise ValueError(&quot;Invalid input&quot;)`用于验证输入数据,若不符合预期则引发异常,确保数据准确并提供清晰错误信息。此外,通过自定义异常类,可以针对特定错误情况提供更具体的信息,增强代码的健壮性和可维护性。
|
Python
在Python中,`try...except`语句用于捕获和处理程序运行时的异常
在Python中,`try...except`语句用于捕获和处理程序运行时的异常
582 5
|
Python
在Python中,自定义函数可以抛出自定义异常
在Python中,自定义函数可以抛出自定义异常
472 5
|
存储 开发者 Python
自定义Python的异常
自定义Python的异常
408 5

推荐镜像

更多