[Python] (XI) Exception Handling

1. Abnormal

What is unusual

That is an abnormal event, which occurs during program execution, affecting the normal program execution.

Under normal circumstances, when the Python program can not be processed normally occurs an exception.

Python is an exception object representing a mistake.

When an exception occurs we need to capture Python script to handle it, otherwise the program will be terminated.

Common exceptions

The exception name description
BaseException Base class for all exceptions
SystemExit Interpreter exit request
KeyboardInterrupt User Interrupt Executing (usually enter ^ C)
Exception General Error base class
StopIteration Iterator no more value
GeneratorExit To notify the exit exception generator (generator) occurs
StandardError All standard exceptions built base class
ArithmeticError All numerical errors base class
FloatingPointError Floating-point calculation error
OverflowError Exceeds the maximum limit value calculation
ZeroDivisionError In addition to (or modulus) of zero (all data types)
AssertionError Assertion failure
AttributeError Object does not have this property
EOFError No built-in input, to reach the EOF marker
EnvironmentError OS Error base class
IOError Input / output operations to fail
OSError Operating system error
WindowsError System call fails
ImportError Import module / object failed
LookupError Invalid class data base query
Index Error Without this sequence index (index)
KeyError Without this key mapping
MemoryError Memory overflow error (for Python interpreter is not fatal)
NameError Undeclared / initialize objects (no attributes)
UnboundLocalError Local access uninitialized variables
ReferenceError Weak reference object (Weak reference) have been trying to access a garbage collection of
RuntimeError General runtime error
NotImplementedError The method has not been implemented
SyntaxError Python syntax error
IndentationError Indentation errors
TabError Tab and space mix
SystemError General interpreter system error
TypeError Invalid type of operation
ValueError Invalid parameter passed
UnicodeError Unicode related errors
UnicodeDecodeError Error when decoding of Unicode
UnicodeEncodeError Unicode encoding error
UnicodeTranslateError Unicode conversion error
Warning Warning base class
DeprecationWarning Warning about deprecated features
FutureWarning Warning about the future structure of the semantics have changed
overflow Warning The old warning about automatically promoted to a long integer (long) of
PendingDeprecationWarning Will be warned about the characteristics of the waste
RuntimeWarning Suspicious behavior (runtime behavior) run-time warning
SyntaxWarning Suspicious Warning grammar
UserWarning User code generated warning

python provides two very important functions to handle exceptions and errors occurring in the python program to run, you can use these functions to debug python programs.

  • Exception Handling
  • Assert (Assertions)

2. Exception Handling

Catch exceptions can use try / except statement.

try / except statement is used to detect errors in the try block, so that the abnormality information except statement capture and processing.

If you do not want to end your program when an exception occurs, just try to capture it in.

Syntax : the try ... the else the except ...

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

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

Try working principle is that when after the start of a try statement, python will be marked in the context of the current program, so that when an exception occurs can be back here, try clause is executed first, followed by the implementation depends on what happens when It is abnormal.

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

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

#!/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

另外,使用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语句捕获所有发生的异常。但这不是一个很好的方式,因为不能通过该程序识别出具体的异常信息。因为它捕获所有的异常。

除此之外, 也可以使用相同的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 b
lock.  

语法try-finally

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

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

注意:你可以使用except语句或者finally语句,但是两者不能同时使用。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块代码。

参数的内容不同于异常。


异常参数

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

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

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

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

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

示例如下:

#!/usr/bin/python
# 定义函数
def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain numbers\n", Argument
# 调用函数
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)参数是一个异常参数值。该参数是可选的,如果不提供,异常的参数是"None"。

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

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

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

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

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

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

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

用户自定义异常

通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自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

异常处理代码执行说明:

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

#This is note foe exception

try:
  code    #需要判断是否会抛出异常的代码,如果没有异常处理,python会直接停止执行程序

except:  #这里会捕捉到上面代码中的异常,并根据异常抛出异常处理信息
#except ExceptionName,args:    #同时也可以接受异常名称和参数,针对不同形式的异常做处理

  code  #这里执行异常处理的相关代码,打印输出等


else#如果没有异常则执行else

  code  #try部分被正常执行后执行的代码

finally:
  code  #退出try语句块总会执行的程序



#函数中做异常检测
def try_exception(num):
  try:
    return int(num)
  except ValueError,arg:
    print arg,"is not a number"
  else:
    print "this is a number inputs"


try_exception('xxx')

#输出异常值
Invalide literal for int() with base 10: 'xxx' is not a number

3.断言

凡是用print()来辅助查看的地方,都可以用断言(assert)来替代:

def foo(s):
    n = int(s)
    assert n != 0, 'n is zero!'
    return 10 / n
def main():
    foo('0')

assert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。

如果断言失败,assert语句本身就会抛出AssertionError

$ python err.py
Traceback (most recent call last):
  ...
AssertionError: n is zero!

程序中如果到处充斥着assert,和print()相比也好不到哪去。不过,启动Python解释器时可以用-O参数来关闭assert

$ python -O err.py
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero

注意:断言的开关“-O”是英文大写字母O,不是数字0。

关闭后,你可以把所有的assert语句当成pass来看。

发布了247 篇原创文章 · 获赞 121 · 访问量 1万+

Guess you like

Origin blog.csdn.net/BeiisBei/article/details/104044989
Recommended