Python - 异常处理

Python - 异常处理 首页 / Python2入门教程 / Python - 异常处理

Python提供了两个非常重要的功能来处理Python程序中的任何意外错误并在其中添加调试功能-

  • 异常处理-本教程将对此进行介绍。以下是Python中可用的标准异常列表:标准异常

标准异常列表-

Sr.No.Exception Name & 描述
1

Exception

所有异常的基类

2

StopIteration

当迭代器的next()方法未指向任何对象时引发。

3

SystemExit

由sys.exit()函数引发。

4

StandardError

除StopIteration和SystemExit外的所有内置异常的基类。

5

ArithmeticError

用于数值计算的所有错误的基类。

6

OverflowError

当计算超出数字类型的最大限制时引发。

7

FloatingPointError

在浮点计算失败时引发。

8

ZeroDivisionError

当所有数值类型都被零除或取零时引发。

9

AssertionError

在Assert语句失败的情况下引发。

10

AttributeError

在属性引用或分配失败的情况下引发。

11

EOFError

当raw_input()或input()函数都没有输入并且到达文件末尾时引发。

12

ImportError

在导入语句失败时引发。

13

KeyboardInterrupt

当用户中断程序执行时引发,通常是按Ctrl + c。

14

LookupError

所有查找错误的基类。

15

IndexError

在序列中未找到索引时引发。

16

KeyError

在词典中找不到指定的键时引发。

17

NameError

在本地或全局名称空间中找不到标识符时引发。

18

UnboundLocalError

在尝试访问函数或方法中的局部变量但未分配任何值时引发。

19

EnvironmentError

所有异常的基类 that occur outside the Python environment.

20

IOError

在输入/输出操作失败时引发,如在尝试打开不存在的文件时使用print语句或open()函数。

21

IOError

因与操作系统相关的错误而引发。

22

SyntaxError

在Python语法错误时引发。

23

IndentationError

未正确指定缩进时引发。

24

SystemError

在解释器发现内部问题时引发,但在遇到此错误时,Python解释器不会退出。

25

SystemExit

通过使用sys.exit()函数退出Python解释器时引发。如果未在代码中处理,则导致解释器退出。

26

TypeError

在尝试执行对指定数据类型无效的操作或功能时引发。

27

ValueError

当数据类型的内置函数具有有效的参数类型,但参数指定了无效值时引发。

28

RuntimeError

在生成的错误不属于任何类别时引发。

29

NotImplementedError

在未真正实现需要在继承的类中实现的抽象方法时引发。

Python 断言

断言是一种健全性检查,可以在完成程序测试后打开或关闭。

想到断言的最简单方法是将其比喻为 raise-if 语句(或更准确地说,是" raise-if-not"语句)。测试表达式,如果输出为假,则引发异常。

断言由assert语句执行,assert语句是Python的最新关键字,在1.5版中引入。

Assert 语句

当遇到断言语句时,Python会判断附带的表达式,希望它是正确的。如果表达式为假,Python会引发 AssertionError 异常。

断言的语法是-

assert Expression[, Arguments]

如果断言失败,Python将ArgumentExpression用作AssertionError的参数。可以使用try-except语句像其他任何异常一样捕获和处理AssertionError异常,但是如果不处理,它们将终止程序并产生回溯。

这是将温度从开氏度转换为华氏度的函数。由于开氏温度为零,因此温度会尽可能低,因此如果看到负温度,该函数将失效-

#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
   assert (Temperature >= 0),"Colder than absolute zero!"
   return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)

执行以上代码后,将产生以下输出-

32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!

异常是事件,该事件在程序执行期间发生,破坏了程序指令的正常流程。通常,当Python脚本遇到无法应付的情况时,它将引发异常。

当Python脚本引发异常时,它必须立即处理该异常,否则它将终止并退出。

处理异常

如果您有一些可能会引发异常的可疑代码,则可以通过将可疑代码放在 try:块中来保护程序。在try:块之后,包含一个 except:语句,然后是一段代码,该代码块尽可能优雅地处理该问题。

这是 try .... except ... else 块的简单语法-

try:
   You do your operations here;
   ......................
except ExceptionI:
   If there is ExceptionI, then execute this block.
except ExceptionII:
   If there is ExceptionII, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

此示例打开文件,在文件中写入内容,然后正常显示,因为根本没有问题-

#!/usr/bin/python

try:
   fh=open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"
   fh.close()

这产生以下输出-

Written content in the file successfully

此示例尝试在您没有写许可权的情况下打开文件,因此引发异常-

#!/usr/bin/python

try:
   fh=open("testfile", "r")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"

这产生以下输出-

Error: can't find file or read data

不含异常的语句

您还可以使用不含异常的except语句,定义如下:

try:
   You do your operations here;
   ......................
except:
   If there is any exception, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

这种 try-except 语句捕获所有发生的异常。但是,使用这种try-except语句并不是一种好的编程习惯,因为它会捕获所有异常,但不能使程序员识别可能出现的问题的根本原因。

包含多个异常语句

您还可以使用相同的 except 语句来处理多个异常,如下所示:

try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

finally 语句

您可以将 finally:块与 try:块一起使用。 finally块是放置任何必须执行的代码的地方,无论try块 是否提出Exception。 try-finally语句的语法是:

try:
   You do your operations here;
   ......................
   Due to any exception, this may be skipped.
finally:
   This would always be executed.
   ......................

您不能同时使用 else 子句和finally子句。

#!/usr/bin/python

try:
   fh=open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
finally:
   print "Error: can\'t find file or read data"

如果您无权以写入模式打开文件,则将产生以下输出-

Error: can't find file or read data

相同的示例可以更清晰地写成如下-

#!/usr/bin/python

try:
   fh=open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print "Going to close the file"
      fh.close()
except IOError:
   print "Error: can\'t find file or read data"

在 try 块中引发异常时,执行立即转到 finally 块。执行 finally 块中的所有语句后,再次引发异常,并在 except 语句中进行处理(如果出现在 try的下一个更高层中) -except 语句。

异常自变量

异常可以有一个自变量,它是一个提供有关该问题的其他信息的值。参数的内容因异常而异。您可以通过在except子句中提供变量来捕获异常的参数,如下所示:

try:
   You do your operations here;
   ......................
except ExceptionType, Argument:
   You can print value of Argument here...

如果编写代码来处理单个异常,则可以在except语句中让变量跟随该异常的名称。如果要捕获多个异常,则可以在该异常的元组之后添加一个变量。

该变量接收异常的值,该值主要包含异常的原因。变量可以以元组的形式接收单个值或多个值。该元组通常包含错误字符串,错误编号和错误位置。

以下是单个异常的示例-

#!/usr/bin/python

# Define a function here.
def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain numbers\n", Argument

# Call above function here.
temp_convert("xyz");

这产生以下输出-

The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

引发异常

您可以使用raise语句以多种方式引发异常。 raise 语句的一般语法如下。

raise [Exception [, args [, traceback]]]

在这里, Exception 是异常的类型(如NameError),而 argument 是异常参数的值。该参数是可选的;如果未提供,则异常参数为None。

最后一个参数traceback也是可选的(在实践中很少使用),如果存在,则为用于异常的traceback对象。

异常可以是字符串,类或对象。 Python核心引发的大多数异常是类,带有作为该类的参数。定义新异常非常容易,可以按照以下步骤进行:

def functionName( level ):
   if level < 1:
      raise "Invalid level!", level
      # The code below to this would not be executed
      # if we raise the exception

注意:为了捕获异常," except"子句必须引用引发类对象或简单字符串的同一异常。如,要捕获上述异常,无涯教程必须编写except子句,如下所示:

try:
   Business Logic here...
except "Invalid level!":
   Exception handling here...
else:
   Rest of the code here...

自定义的异常

Python还允许您通过从标准内置异常派生类来创建自己的异常。

这是与 RuntimeError 有关的示例。在这里,创建了一个从 RuntimeError 继承的类。当在捕获异常时需要显示更多特定信息时,此功能很有用。

在try块中,引发用户定义的异常并将其捕获到except块中。变量e用于创建 Networkerror 类的。

class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args=arg

因此,一旦您定义了上述类,就可以引发异常,如下所示:

try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print e.args

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

从0开始学微服务 -〔胡忠想〕

算法面试通关40讲 -〔覃超〕

深入浅出计算机组成原理 -〔徐文浩〕

架构实战案例解析 -〔王庆友〕

Redis核心技术与实战 -〔蒋德钧〕

零基础实战机器学习 -〔黄佳〕

Go进阶 · 分布式爬虫实战 -〔郑建勋〕

零基础GPT应用入门课 -〔林健(键盘)〕

手把手带你写一个 MiniTomcat -〔郭屹〕

好记忆不如烂笔头。留下您的足迹吧 :)