Python exception summary

Python exception handling

Python provides two very important functions to deal with exceptions and errors that occur in the running of Python programs. You can use this function to debug python programs.

  • Exception handling: This site's Python tutorial will be introduced in detail.
  • Assertions: This site's Python tutorial will be introduced in detail.

Python standard exception

Exception name description
BaseException Base class for all exceptions
SystemExit Interpreter request to exit
KeyboardInterrupt User interrupts execution (usually input ^ C)
Exception Base class for general errors
StopIteration Iterator has no more values
GeneratorExit An exception occurs in the generator to notify the exit
StandardError Base class for all built-in standard exceptions
ArithmeticError Base class for all numerical calculation errors
FloatingPointError Floating point calculation error
OverflowError Numerical operation exceeds the maximum limit
ZeroDivisionError Divide (or modulo) zero (all data types)
AssertionError Assertion statement failed
AttributeError Object does not have this property
EOFError No built-in input, reach EOF mark
EnvironmentError Operating system error base class
IOError Input / output operation failed
OSError Operating system error
WindowsError System call failed
ImportError Failed to import module / object
LookupError Base class for invalid data query
Index Error There is no such index in the sequence
KeyError There is no such key in the map
MemoryError Memory overflow error (not fatal to Python interpreter)
NameError Undeclared / initialized object (no attributes)
UnboundLocalError Access uninitialized local variables
ReferenceError Weak reference attempts to access objects that have been garbage collected
RuntimeError General runtime errors
NotImplementedError Unimplemented methods
SyntaxError Python syntax error
IndentationError Indentation error
TabError Tab and space mixed
SystemError General interpreter system errors
TypeError Invalid operation on type
ValueError Invalid parameters passed in
UnicodeError Unicode related errors
UnicodeDecodeError Error when decoding Unicode
UnicodeEncodeError Error when encoding Unicode
UnicodeTranslateError Error during Unicode conversion
Warning Base class for warnings
DeprecationWarning Warning about deprecated features
FutureWarning Warning about constructing future semantic changes
overflow Warning Old warning about automatic promotion to long
PendingDeprecationWarning Warning about features being obsolete
RuntimeWarning Warning of suspicious runtime behavior
SyntaxWarning Suspicious syntax warning
UserWarning Warning generated by user code

What is abnormal?

An exception is an event that occurs during the execution of a program, affecting the normal execution of the program.

In general, an exception occurs when Python cannot process the program normally.

The exception is a Python object, indicating an error.

When an exception occurs in the Python script, we need to capture and handle it, otherwise the program will terminate execution.


Exception handling

Catching exceptions can use try / except statements.

The try / except statement is used to detect errors in the try statement block, so that the except statement captures exception information and handles it.

If you don't want to end your program when an exception occurs, just catch it in try.

grammar:

The following is a simple try .... except ... else syntax:

try:
<语句>        #运行别的代码 except <名字>: <语句> #如果在try部份引发了'name'异常 except <名字>,<数据>: <语句> #如果引发了'name'异常,获得附加的数据 else: <语句> #如果没有异常发生

try的工作原理是,当开始一个try语句后,python就在当前程序的上下文中作标记,这样当异常出现时就可以回到这里,try子句先执行,接下来会发生什么依赖于执行时是否出现异常。

  • 如果当try后的语句执行时发生异常,python就跳回到try并执行第一个匹配该异常的except子句,异常处理完毕,控制流就通过整个try语句(除非在处理异常时又引发新的异常)。
  • 如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印默认的出错信息)。
  • 如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句。

实例

下面是简单的例子,它打开一个文件,在该文件中的内容写入内容,且并未发生异常:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!!") except IOError: print "Error: 没有找到文件或读取文件失败" else: print "内容写入文件成功" fh.close()

以上程序输出结果:

$ python test.py 
内容写入文件成功
$ cat testfile       # 查看写入的内容 这是一个测试文件,用于测试异常!!

实例

下面是简单的例子,它打开一个文件,在该文件中的内容写入内容,但文件没有写入权限,发生了异常:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!!") except IOError: print "Error: 没有找到文件或读取文件失败" else: print "内容写入文件成功" fh.close()

在执行代码前为了测试方便,我们可以先去掉 testfile 文件的写权限,命令如下:

chmod -w testfile

再执行以上代码:

$ python test.py 
Error: 没有找到文件或读取文件失败

使用except而不带任何异常类型

你可以不带任何异常类型使用except,如下实例:

try:
    正常的操作
   ...................... except: 发生异常,执行这块代码 ...................... else: 如果没有异常执行这块代码

以上方式try-except语句捕获所有发生的异常。但这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息。因为它捕获所有的异常。


使用except而带多种异常类型

你也可以使用相同的except语句来处理多个异常信息,如下所示:

try:
    正常的操作
   ...................... except(Exception1[, Exception2[,...ExceptionN]]]): 发生以上多个异常中的一个,执行这块代码 ...................... else: 如果没有异常执行这块代码

try-finally 语句

try-finally 语句无论是否发生异常都将执行最后的代码。

try:
<语句>
finally: <语句> #退出try时总会执行 raise

实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!!") finally: print "Error: 没有找到文件或读取文件失败"

如果打开的文件没有可写权限,输出如下所示:

$ python test.py 
Error: 没有找到文件或读取文件失败

同样的例子也可以写成如下方式:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try: fh = open("testfile", "w") try: fh.write("这是一个测试文件,用于测试异常!!") finally: print "关闭文件" fh.close() except IOError: print "Error: 没有找到文件或读取文件失败"

当在try块中抛出一个异常,立即执行finally块代码。

finally块中的所有语句执行后,异常被再次触发,并执行except块代码。

参数的内容不同于异常。


异常的参数

一个异常可以带上参数,可作为输出的异常信息参数。

你可以通过except语句来捕获异常的参数,如下所示:

try:
    正常的操作
   ...................... except ExceptionType, Argument: 你可以在这输出 Argument 的值...

变量接收的异常值通常包含在异常的语句中。在元组的表单中变量可以接收一个或者多个值。

元组通常包含错误字符串,错误数字,错误位置。

实例

以下为单个异常的实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 定义函数 def temp_convert(var): try: return int(var) except ValueError, Argument: print "参数没有包含数字\n", Argument # 调用函数 temp_convert("xyz");

以上程序执行结果如下:

$ python test.py 
参数没有包含数字
invalid literal for int() with base 10: 'xyz'

触发异常

我们可以使用raise语句自己触发异常

raise语法格式如下:

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

语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。

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

实例

一个异常可以是一个字符串,类或对象。 Python的内核提供的异常,大多数都是实例化的类,这是一个类的实例的参数。

定义一个异常非常简单,如下所示:

def functionName( level ): if level < 1: raise Exception("Invalid level!", level) # 触发异常后,后面的代码就不会再执行

注意:为了能够捕获异常,"except"语句必须有用相同的异常来抛出类对象或者字符串。

例如我们捕获以上异常,"except"语句如下所示:

try:
    正常逻辑
except Exception,err: 触发自定义异常 else: 其余代码

实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 定义函数 def mye( level ): if level < 1: raise Exception,"Invalid level!" # 触发异常后,后面的代码就不会再执行 try: mye(0) # 触发异常 except Exception,err: print 1,err else: print 2

执行以上代码,输出结果为:

$ python test.py 
1 Invalid level!

用户自定义异常

通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自Exception类,通过直接或间接的方式。

以下为与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



原文来自:https://www.runoob.com/python/python-exceptions.html

Guess you like

Origin www.cnblogs.com/zxc01/p/12719436.html