百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

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

off999 2024-11-19 08:35 27 浏览 0 评论

简介

和其他的语言一样,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

其中BaseExceptionExceptionArithmeticErrorBufferErrorLookupError 主要被作为其他异常的基类。

语法错误

在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

tryexcept语句有一个可选的 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

本文已收录于 http://www.flydean.com/09-python-error-exception/

最通俗的解读,最深刻的干货,最简洁的教程,众多你不知道的小技巧等你来发现!

欢迎关注我的公众号:「程序那些事」,懂技术,更懂你!

相关推荐

PYTHON-简易计算器的元素介绍

[烟花]了解模板代码的组成importPySimpleGUIassg#1)导入库layout=[[],[],[]]#2)定义布局,确定行数window=sg.Window(&#...

如何使用Python编写一个简单的计算器程序

Python是一种简单易学的编程语言,非常适合初学者入门。本文将教您如何使用Python编写一个简单易用的计算器程序,帮助您快速进行基本的数学运算。无需任何高深的数学知识,只需跟随本文的步骤,即可轻松...

用Python打造一个简洁美观的桌面计算器

最近在学习PythonGUI编程,顺手用Tkinter实现了一个简易桌面计算器,功能虽然不复杂,但非常适合新手练手。如果你正在学习Python,不妨一起来看看这个项目吧!项目背景Tkint...

用Python制作一个带图形界面的计算器

大家好,今天我要带大家使用Python制作一个具有图形界面的计算器应用程序。这个项目不仅可以帮助你巩固Python编程基础,还可以让你初步体验图形化编程的乐趣。我们将使用Python的tkinter库...

用python怎么做最简单的桌面计算器

有网友问,用python怎么做一个最简单的桌面计算器。如果只强调简单,在本机运行,不考虑安全性和容错等的话,你能想到的最简单的方案是什么呢?我觉得用tkinter加eval就够简单的。现在开整。首先创...

说好的《Think Python 2e》更新呢!

编程派微信号:codingpy本周三脱更了,不过发现好多朋友在那天去访问《ThinkPython2e》的在线版,感觉有点对不住呢(实在是没抽出时间来更新)。不过还好本周六的更新可以实现,要不就放一...

构建AI系统(三):使用Python设置您的第一个MCP服务器

是时候动手实践了!在这一部分中,我们将设置开发环境并创建我们的第一个MCP服务器。如果您从未编写过代码,也不用担心-我们将一步一步来。我们要构建什么还记得第1部分中Maria的咖啡馆吗?我们正在创...

函数还是类?90%程序员都踩过的Python认知误区

那个深夜,你在调试代码,一行行检查变量类型。突然,一个TypeError错误蹦出来,你盯着那句"strobjectisnotcallable",咖啡杯在桌上留下了一圈深色...

《Think Python 2e》中译版更新啦!

【回复“python”,送你十本电子书】又到了周三,一周快过去一半了。小编按计划更新《ThinkPython2e》最新版中译。今天更新的是第五章:条件和递归。具体内容请点击阅读原文查看。其他章节的...

Python mysql批量更新数据(兼容动态数据库字段、表名)

一、应用场景上篇文章我们学会了在pymysql事务中批量插入数据的复用代码,既然有了批量插入,那批量更新和批量删除的操作也少不了。二、解决思路为了解决批量删除和批量更新的问题,提出如下思路:所有更新语...

Python Pandas 库:解锁 combine、update 和compare函数的强大功能

在Python的数据处理领域,Pandas库提供了丰富且实用的函数,帮助我们高效地处理和分析数据。今天,咱们就来深入探索Pandas库中四个功能独特的函数:combine、combine_fi...

记录Python3.7.4更新到Python.3.7.8

Python官网Python安装包下载下载文件名称运行后选择升级选项等待安装安装完毕打开IDLE使用Python...

Python千叶网原图爬虫:界面化升级实践

该工具以Python爬虫技术为核心,实现千叶网原图的精准抓取,突破缩略图限制,直达高清资源。新增图形化界面(GUI)后,操作门槛大幅降低:-界面集成URL输入、存储路径选择、线程设置等核心功能,...

__future__模块:Python语言版本演进的桥梁

摘要Python作为一门持续演进的编程语言,在版本迭代过程中不可避免地引入了破坏性变更。__future__模块作为Python兼容性管理的核心机制,为开发者提供了在旧版本中体验新特性的能力。本文深入...

Python 集合隐藏技能:add 与 update 的致命区别,90% 开发者都踩过坑

add函数的使用场景及错误注意添加单一元素:正确示例:pythons={1,2}s.add(3)print(s)#{1,2,3}错误场景:试图添加可变对象(如列表)会报错(Pytho...

取消回复欢迎 发表评论: