设为首页 加入收藏

TOP

Python 标准异常总结(二)
2017-04-16 10:23:19 】 浏览:499
Tags:Python 标准 异常 总结
quot;)
else:
  print ("Written content in the file successfully")
  fh.close()
  结果:
  Error: can't find file or read data  #这里没有报出是那个类型的标准错误。


try-finally子句:
    使用 try: 块. finally 块是必须执行,而不管 try 块是否引发异常或没有。try-finally 语句的语法是这样的。


try:
  You do your operations here;
  ......................
  Due to any exception, this may be skipped.



except ExceptionI:
  If there is ExceptionI, then execute this block.
except ExceptionII:
  If there is ExceptionII, then execute this block.


finally:
1    This would always be executed.


 try...except...finally无论try块能否正常的执行,finally是一定会执行的模块。
123456789101112 try:
  fh = open("testfile", "r")
  fh.write("This is my test file for exception handling!!")
except (ValueError,ImportError,RuntimeError):
  print ("Error: can\'t find file or read data")
finally:
  print ("Written content in the file successfully")
  fh.close() #关闭文件
  结果:文件中没有写入内容,
  控制台输出以下内容:
Error: can't find file or read data
Written content in the file successfully


引发异常
可以通过使用 raise 语句触发几个方面的异常。对于 raise 语句的一般语法如下。
语法
raise [Exception [, args [, traceback]]]这里,Exception 是异常的类型(例如,NameError)argument 为异常的参数值。该参数是可选的;如果没有提供,异常的参数是None。
最后一个参数 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


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇通过RTCP进行媒体流实时丢包重传.. 下一篇Python3调用接口查询IP信息

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目