Python基础之:Python中的异常和错误
off999 2024-11-19 08:35 19 浏览 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
其中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
本文已收录于 http://www.flydean.com/09-python-error-exception/
最通俗的解读,最深刻的干货,最简洁的教程,众多你不知道的小技巧等你来发现!
欢迎关注我的公众号:「程序那些事」,懂技术,更懂你!
- 上一篇:76. 异常 #python
- 下一篇:Python的错误和异常
相关推荐
- python入门到脱坑经典案例比较大小的6种经典方法
-
在Python中比较两个数的大小是最基础的编程操作之一,以下是6种经典方法及其应用场景,从基础到进阶的完整指南:1.基础比较运算符直接使用>、<、==等运算符:a,b=...
- Python学习 -- 高阶、闭包、回调、偏函数与装饰器探究
-
Python函数作为编程的核心,涵盖了众多令人兴奋的概念,如高阶函数、闭包、回调、偏函数和装饰器。本篇博客将深入研究这些概念,结合实际案例为你解析函数的精妙,以及如何巧妙地运用它们来构建更强大、灵活的...
- python编程中你遇到最恶心的事情是什么
-
在编程的广袤天地里,总有那么些让人抓狂、崩溃,甚至想“砸电脑”的恶心事儿。要说这其中最让人头疼的,莫过于代码中的“神秘Bug”1.可变默认参数的幽灵行为defappend_to(element,...
- python生成器14个常见问题及详解(python生成器定义)
-
以下是Python生成器(Generator)常见问题的详细解答,涵盖使用中的典型疑惑和解决方案:一、基础问题1.生成器只能遍历一次吗?答:是的,生成器是一次性对象,遍历完后需重新创建:defge...
- Python 中 必须掌握的 20 个核心函数及其含义,不允许你不会
-
以下是Python中必须掌握的20个核心函数及其含义,涵盖数据处理、文件操作、面向对象等关键领域,每个函数均附代码示例和应用场景:一、基础必备函数1.print()作用:输出内容到控制台示例...
- 自学Python你卡在了哪一步?被卡了几次?
-
自学Python的放弃点通常集中在以下几个阶段(按学习顺序排列),结合放弃原因和应对建议整理如下:---###**1.环境配置阶段(第1-3天)**-**放弃原因**:-安装Pytho...
- python 10个堪称完美的for循环实践
-
在Python中,for循环的高效使用能显著提升代码性能和可读性。以下是10个堪称完美的for循环实践,涵盖数据处理、算法优化和Pythonic编程风格:1.遍历列表同时获取索引(enumerate...
- python后端学什么(python后端岗位多吗)
-
在当今数字化的时代,Python后端开发成为了众多开发者追逐的热门领域。那么,想要在这个领域崭露头角,我们究竟应该学些什么呢?学习Python后端开发需要掌握全栈技术栈,涵盖从基础语法到分布式...
- Python 列表(List)详解(python中列表用法)
-
列表是Python中最基本、最常用的数据结构之一,它是一个有序的、可变的元素集合。一、列表的基本操作1.创建列表#空列表empty_list=[]empty_list=list()...
- Python 数据转换详解(python将数据转换为字符串)
-
数据转换是编程中非常重要的操作,Python提供了多种方式来实现不同类型之间的转换。下面我将详细讲解Python中的各种数据转换方法。一、基本数据类型转换1.数字类型之间的转换#整数转浮点数...
- python入门 到脱坑 基本数据类型—集合
-
以下是Python集合(Set)的入门详解,包含基础概念、常用操作和实用技巧,帮助初学者快速掌握这一重要数据类型:一、集合基础1.定义集合#空集合(必须用set(),不能用{})empty_se...
- 百看不如一练的247个Python实战案例(附高清PDF完整版教程)
-
百看不如一练,247个python实战案例拿去练手吧希望对大家有帮助!喜欢python和正在学习python的小伙伴可以练练手哦!...
- Python 中 最容易被忽略却极具价值的 8 个特性,80%都不知道
-
1.__slots__:禁止动态属性分配作用:节省内存+防止属性拼写错误示例:classUser:__slots__=['name','age']...
- python中数值比较大小的8种经典比较方法,不允许你还不知道
-
在Python中比较数值大小是基础但重要的操作。以下是8种经典比较方法及其应用场景,从基础到进阶的完整指南:1.基础比较运算符Python提供6种基础比较运算符:a,b=5,3...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python自定义函数 (53)
- python进度条 (67)
- python吧 (67)
- python的for循环 (56)
- python串口编程 (60)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python字典增加键值对 (53)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python qt (52)
- python人脸识别 (54)
- python多态 (60)
- python命令行参数 (53)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- centos7安装python (53)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)