Python 3 - 异常处理

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

  • 异常处理 : 这将在本教程中介绍.以下是Python和minus中可用的列表标准异常; 标准例外.

  • 断言 : 这将在 Python 3中的断言教程中介绍.

标准异常

以下是Python中可用的标准异常列表.  :

Sr.No.例外名称&说明
1

Exception

所有例外的基类

2

StopIteration

迭代器的next()方法时引发不指向任何对象.

3

SystemExit

由sys.exit()函数引发.

4

StandardError

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

5

ArithmeticError

数值计算发生的所有错误的基类.

6

OverflowError

当计算超过数字类型的最大限制时触发.

7

FloatingPointError

浮点计算失败时引发.

8

ZeroDivisonError

当所有数字类型的除法或模数为零时引发.

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

在Python环境之外发生的所有异常的基类.

20

IOError

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

21

OSError

引发与操作系统相关的错误.

22

SyntaxError

当Python语法出错时引发.

23

IndentationError

未指定缩进时触发正确.

24

SystemError

解释器找到内部时引发l问题,但遇到此错误时,Python解释器不会退出.

25

SystemExit

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

26

TypeError

尝试对指定数据类型无效的操作或函数时触发.

27

ValueError

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

28

RuntimeError

当生成的错误不属于任何类别时引发.

29

NotImplementedError

当抽象方法出现时需要在继承的类中实现,实际上并没有实现.

Python中的断言

断言是一种可以打开的理智检查或者在完成程序测试后关闭.

  • 想到断言的最简单方法是将它比作 raise-if 语句(或者更准确地说,是一个if-if-not语句).测试表达式,如果结果为false,则引发异常.

  • 断言由断言语句执行,这是Python的最新关键字,1.5版本.

  • 程序员经常在函数开头放置断言来检查有效输入,并在函数调用后检查有效输出.

断言语句

当遇到断言语句时,Python会评估附带的表达式,这是有希望的.如果表达式为false,则Python引发 AssertionError 异常.

断言的语法是 :

assert Expression[, Arguments]


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

示例

这是一个从度转换给定温度的函数开尔文到华氏度.由于0°K和它一样冷,如果它看到负温度和负值,函数会失效;

#!/usr/bin/python3

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对象.

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

处理异常

如果您有一些可能引发异常的可疑代码,您可以通过将可疑代码放入

语法

这是尝试的简单语法....除了......其他块 :

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.


以下几个关于上述语法的重要观点 :

  • 单个try语句可以有多个except语句.当try块包含可能引发不同类型异常的语句时,这很有用.

  • 您还可以提供一个通用except子句,它处理任何异常.

  • 在except子句之后,您可以包含else子句.如果try:block中的代码没有引发异常,则执行else-block中的代码.

  • else-block是代码的好地方这不需要try:block的保护.

示例

此示例打开一个文件,在文件中写入内容并优雅地出来,因为根本没有问题&减去;

#!/usr/bin/python3

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/python3

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语句虽然不被认为是一种很好的编程习惯,因为它捕获了所有异常但却没有让程序员找出可能发生的问题的根本原因.

除了具有多个异常的子句

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

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.


try-finally Clause

您可以使用 finally:块以及a 尝试:块.无论try-block是否引发异常, finally:块都是放置必须执行的代码的地方. try-finally语句的语法是这个 :

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


注意 : 您可以提供except子句或finally子句,但不能同时提供两者.你也不能使用 else 子句以及finally子句.

示例

#!/usr/bin/python3

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")
   fh.close()


如果您无权以书面模式打开文件,那么这将产生以下结果 :

Error: can't find file or read data


相同的例子可以写得更干净如下:

#!/usr/bin/python3

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


这会产生以下结果&minus ;

Going to close the file


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

异常的参数

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

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


如果编写代码来处理单个异常,则可以在except语句中使用变量的名称.如果要捕获多个异常,则可以使用变量跟随异常的元组.

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

示例

以下是单个例外的示例 :

#!/usr/bin/python3

# Define a function here.
def temp_convert(var):
   try:
      return int(var)
   except ValueError as 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 语句的一般语法如下 :

语法

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


这里, Exception 是异常的类型(例如,NameError)和参数是异常参数的值.参数是可选的;如果没有提供,则异常参数为None.

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

示例

异常可以是字符串,类或对象. Python核心引发的大多数异常都是类,其参数是类的一个实例.定义新的异常非常简单,可以按照以下方式完成;

def functionName( level ):
   if level <1:
      raise Exception(level)
      # The code below to this would not be executed
      # if we raise the exception
   return level


注意 : 为了捕获异常,"except"子句必须引用作为类对象或简单字符串抛出的相同异常.例如,要捕获上述异常,我们必须编写except子句,如下所示 :

try:
   Business Logic here...
except Exception as e:
   Exception handling here using e.args...
else:
   Rest of the code here...


以下示例说明了使用引发异常 :

#!/usr/bin/python3

def functionName( level ):
   if level <1:
      raise Exception(level)
      # The code below to this would not be executed
      # if we raise the exception
   return level

try:
   l = functionName(-10)
   print ("level = ",l)
except Exception as e:
   print ("error in level argument",e.args[0])


这将产生以下结果

error in level argument -10


用户定义的异常

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