码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础教程 第8章: 异常 学习笔记

时间:2015-12-18 18:08:17      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:

文章部分内容参考至: http://www.runoob.com/python/python-exceptions.html

 

主动抛异常:

class MyException(Exception):
    pass

#相当于c++中的throw, 主动抛异常
raise MyException

>>>

Traceback (most recent call last):
File "hello.py", line 4, in <module>
raise MyException
MyException

使用dir列出模块中的所有函数:

import exceptions
print dir(exceptions)

列出了所有异常类:

>>>
[‘ArithmeticError‘, ‘AssertionError‘, ‘AttributeError‘, ‘BaseException‘, ‘BufferError‘, ‘BytesWarning‘, ‘DeprecationWarning‘, ‘EOFError‘, ‘EnvironmentError‘, ‘Exception‘, ‘FloatingPointError‘, ‘FutureWarning‘, ‘GeneratorExit‘, ‘IOError‘, ‘ImportError‘, ‘ImportWarning‘, ‘IndentationError‘, ‘IndexError‘, ‘KeyError‘, ‘KeyboardInterrupt‘, ‘LookupError‘, ‘MemoryError‘, ‘NameError‘, ‘NotImplementedError‘, ‘OSError‘, ‘OverflowError‘, ‘PendingDeprecationWarning‘, ‘ReferenceError‘, ‘RuntimeError‘, ‘RuntimeWarning‘, ‘StandardError‘, ‘StopIteration‘, ‘SyntaxError‘, ‘SyntaxWarning‘, ‘SystemError‘, ‘SystemExit‘, ‘TabError‘, ‘TypeError‘, ‘UnboundLocalError‘, ‘UnicodeDecodeError‘, ‘UnicodeEncodeError‘, ‘UnicodeError‘, ‘UnicodeTranslateError‘, ‘UnicodeWarning‘, ‘UserWarning‘, ‘ValueError‘, ‘Warning‘, ‘WindowsError‘, ‘ZeroDivisionError‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘]

自定义异常类,只需要继承自Exception类即可。

捕获异常:

try:
    n = input("input number: ")
    print 3 / n
except ZeroDivisionError:
    print "Div Zero Error"

>>>
input number: 1
3
>>>
input number: 0
Div Zero Error

 异常继续向上层抛:

def fun(n):
    try:
        print 3 / n
    except ZeroDivisionError:
        print "fun::Error"
        #继续向上抛该异常
        raise
            
def Myfun():
    try:
        n = input("input number: ")
        fun(n)
    except ZeroDivisionError:
        print "Myfun::Error"

Myfun()

>>>
input number: 0
fun::Error
Myfun::Error

 多个except子句和一个try块捕获多个异常:

def Myfun():
    try:
        x = input("input x number: ")
        y = input("input y number: ")
        print x / y
        print "Hello"
    #多个except块
    except ZeroDivisionError:
        print "ZeroDivisionError"
    except TypeError:
        print "TypeError"

def fun():
    try:
        x = input("input x number: ")
        y = input("input y number: ")
        print x / y
        print "Hello"
    #同时捕获两个异常
    except (ZeroDivisionError, TypeError):
        print "ZeroDivisionError or TypeError"

fun()

input x number: 3
input y number: 1
3
Hello
>>>
input x number: 3
input y number: 0
ZeroDivisionError or TypeError
>>>
input x number: 3
input y number: "a"
ZeroDivisionError or TypeError

捕获异常对象:如果程序中有记录错误日志的功能,获取到异常对象后,然后调用该对象的记录日志的方法即可

def fun():
    try:
        x = input("input x number: ")
        y = input("input y number: ")
        print x / y
        print "Hello"
    #同时捕获两个异常
    except (ZeroDivisionError, TypeError), e:
        print "ZeroDivisionError or TypeError"
        print e

fun()

>>>
input x number: 3
input y number: 0
ZeroDivisionError or TypeError
integer division or modulo by zero

异常全捕获:

try:
    x = input("x: ")
    y = input("y: ")
    print x / y
    
except ZeroDivisionError:
    print "ZeroDivisionError"
except TypeError:
    print "TypeError"
except Exception, e:   #except:
    print "Other Error"
    print e
while True:
    try:
        x = input("intput x: ")
        y = input("intput y: ")
        print x / y
    #死循环接收用户输入并输出结果
    except Exception:
        print "Exception"
    #如果异常则继续循环, 否则就退出循环
    else:
        break

finally: 不管是否发生有异常,都一定会被执行到的语句

#跟java一样, Python中也有finally关键字

try:
    x = input("x: ")
    print 3 / x
except Exception:
    print "Exception"
finally:
    print "我被执行了"

>>>
x: 1
3
我被执行了
>>>
x: 0
Exception
我被执行了

一个异常可以带上参数,可作为输出的异常信息参数,可以通过except语句来捕获异常的参数:

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

变量接收的异常值通常包含在异常的语句中。在元组的表单中变量可以接收一个或者多个值。元组通常包含错误字符串,错误数字,错误位置。

# 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‘

 

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

如果当try后的语句执行时发生异常,python就跳回到try并执行第一个匹配该异常的except子句,异常处理完毕,控制流就通过整个try语句(除非在处理异常时又引发新的异常)。

如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印缺省的出错信息)。

如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句。

 

 

有些时候,条件语句可以实现和异常同样的功能,但是条件语句可能在自然性和可读性上差些,而从另一方面来看,某些程序中使用if/else实现会比使用try/except要好。

Python基础教程 第8章: 异常 学习笔记

标签:

原文地址:http://www.cnblogs.com/dacainiao/p/5057455.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!