当前位置:首页 > Python教程 > python技巧

python中的异常如何处理

一、异常基础

在编程程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面。

            1
            try
            :

            2
            #
            正常逻辑代码
            3     input = raw_input("输入数字:")
4     data = int(input)
56except Exception,e:
7#逻辑代码块出现错误,8print请输入数字!!!

两个数字相加异常处理:

             1
            while
             True:

             2     number1 = raw_input(number1:)
 3     number2 = raw_input(number2:)
 4try:
 5         num1 = int(number1)
 6         num2 = int(number2)
 7         res = number1 + number2
 8print res
 9except Exception, e:
10print出现异常,信息如下:11print e

二、异常种类

            ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
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
ZeroDivisionError
        
技术分享KeyError技术分享
dic = {k1:123,k2:321}
try:
    dic[k3]
except KeyError,e:
    print出现异常,信息如下:print e

技术分享 技术分享
li = [gavin-guo]
try:
    li[100]
except IndexError,e:
    print出现异常,信息如下:print e
IndexError
技术分享 技术分享
str = abctry:
    int(str)
except ValueError,e:
    print出现异常,信息如下:print e
ValueError

上述实例异常只能处理指定异常,如果非指定异常则无法处理

str = abctry:
    int(str)
except IndexError,e:
    print出现异常,信息如下:print e

出现错误信息了,则应该这样处理.

             1 str = abc 2try:
 3    int(str)
 4except IndexError,e:
 5print出现异常,信息如下: 6print e
 7except ValueError,e:
 8print出现异常,信息如下: 9print e
10except KeyError,e:
11print出现异常,信息如下:12print e

python中有一个异常能捕捉到所有异常:Exception

            1 str = abc2try:
3    int(str)
4except Exception,e:
5print e

三、异常的其他结构

             1
            try
            :

             2
            #
             逻辑代码,连接数据库,执行sql语句
             3
            pass
             4
            except
             KeyError,e:

             5
            #
             异常时,执行该块
             6
            pass
             7
            else
            :

             8
            #
             逻辑码块中未出现异常执行这里的代码
             9
            pass
            10
            finally
            :
11 # 永远执行,主代码块执行完之后执行.断开数据库连接,释放资源
12 pass

四、主动触发异常

raise Exception(‘出现错误‘)

             1
            class
             A:

             2
            def
             a1(self):

             3
            return
             False

             4
             5
            try
            :

             6     a = 1 7#a = int(a) 8     re = A()
 9     ret = re.a1()
10if ret:
11print成功12else:
13raise Exception() #执行这一行代码,等于直接倒转到下面的except Exception14except Exception,e:
15print出现错误!!16print e

五、自定义异常

自己定义一个异常,然后调用这个异常

             1
            class
             Gavinerror(Exception):

             2
             3
            def
            __init__(self,date=None):
 4         self.date = date
 5def__str__(self):
 6if self.date:
 7return  self.date
 8else:
 9returnGavin error10try:
11raise Gavinerror()
12except Exception,e:
13print e

 

原文:http://www.cnblogs.com/guociming/p/5132973.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐