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
本文已收录于 http://www.flydean.com/09-python-error-exception/
最通俗的解读,最深刻的干货,最简洁的教程,众多你不知道的小技巧等你来发现!
欢迎关注我的公众号:「程序那些事」,懂技术,更懂你!
Python基础之:Python中的异常和错误的更多相关文章
- 孤荷凌寒自学python第三十二天python的代码块中的异常的捕获
孤荷凌寒自学python第三十二天python的代码块中的异常的捕获 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天简单了解了Python的错误陷阱,了解到其与过去学过的其它语言非常类似 ...
- 二十一. Python基础(21)--Python基础(21)
二十一. Python基础(21)--Python基础(21) 1 ● 类的命名空间 #对于类的静态属性: #类.属性: 调用的就是类中的属性 #对象.属性: 先从自己的内存空间里找名 ...
- 改写《python基础教程》中的一个例子
一.前言 初学python,看<python基础教程>,第20章实现了将文本转化成html的功能.由于本人之前有DIY一个markdown转html的算法,所以对这个例子有兴趣.可仔细一看 ...
- python基础20 -------python中的异常处理
一.python程序中的会出现的错误. 1.语法错误:这种错误根本过不了python解释器的语法检测阶段,必须在程序执行之前进行改正. 2.逻辑错误:这种错误虽然过了语法检测阶段但是程序在执行的过程中 ...
- Python基础+Pythonweb+Python扩展+Python选修四大专题 超强麦子学院Python35G视频教程
[保持在百度网盘中的, 可以在观看,嘿嘿 内容有点多,要想下载, 回复后就可以查看下载地址,资源收集不易,请好好珍惜] 下载地址:http://www.fu83.cc/ 感觉文章好,可以小手一抖 -- ...
- Python基础-1 python由来 Python安装入门 注释 pyc文件 python变量 获取用户输入 流程控制if while
1.Python由来 Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚 ...
- python基础实践 -python是一门动态解释性的强类型定义语言
python是一门动态解释性的强类型定义语言 Python能做什么? Python是一门综合性的语言,你几乎能在计算机上通过Python做任何事情,以下是Python应该最广泛的几个方面: 1.网络应 ...
- python基础-初识Python和不同语言之间的区别
一.Python的创始人谁? Python之父:吉多·范罗苏姆GuidovanRossum 吉多·范罗苏姆是一名荷兰计算机程序员,他作为Python程序设计语言的作者而为人们熟知.在Python社区, ...
- python基础7 ---python函数
python基础知识 一.闭包函数 1.闭包函数的定义:在一个内部函数中,在对外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包. 2.闭包函数的特点:自带作用域和延迟计算 补 ...
随机推荐
- iPhone 12 导入通讯录排序 Bug
iPhone 12 导入通讯录排序 Bug iOS iOS 通讯录排序问题 Huawei OK solution iOS 切换中英文,修复排序通讯录 bug Awesome iOS Contacts ...
- SwiftUI & MVVM
SwiftUI & MVVM design paradigm / 设计模式 MVVM Model View ViewModel MVVM Architecture 架构 MVC Model V ...
- React Toolchains
React Toolchains Create React App / component library https://create-react-app.dev/docs/getting-star ...
- keepalived-1.3.5+MHA部署mysql集群
MHA: MHA工作原理总结为以下几条: 从宕机崩溃的master保存二进制日志事件(binlog events): 识别含有最新更新的slave: 应用差异的中继日志(relay log)到其他sl ...
- sublime 使用过程中遇到的问题
1.当我把鼠标放置在下图所示的class上几秒钟后,sublime就会在全局查找当前的class字符,这时sublime就会出现卡顿或无响应 解决方法: 点击preferences下的settings ...
- Scrapy 项目:QuotesBot
QuotesBot This is a Scrapy project to scrape quotes from famous people from http://quotes.toscrape.c ...
- Spring—Document root element "beans", must match DOCTYPE root "null"分析及解决方法
网上很多人说要把applicationContex.xml文件中加上如下第二行的<!DOCTYPE/>标签,说明DTD.<?xml version="1.0" e ...
- Vuex理解与使用
1.Vuex是什么 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,用于管理页面的数据状态.提供统一数据操作的生态系统.在组件中可以任意获取仓库中的数据.和Vuex类似的还有redux ...
- C# 处理PPT水印(三)—— 在PPT中添加多行(平铺)文本水印效果
在PPT幻灯片中,可通过添加形状的方式,来实现类似水印的效果,可添加单一文本水印效果,即幻灯片中只有一个文本水印:也可以添加多行(平铺)文本水印效果,即幻灯片中以一定方式平铺排列多个文本水印效果.本文 ...
- h5返回上一页ios页面不刷新
var isPage=false; window.addEventListener('pageshow', function () { if (isPage) { window.loc ...