异常处理

1、异常基础

在编程过程中为了增加友好性,在程序出现BUG时一般不会降错误信息显示给用户,而是显示一个提示的页面,通俗来说就是不让用户看见大黄页!!!

try:
    pass
except Exception,ex:
    pass

需求:将两个数字相加,并加上异常处理

num1=raw_input('请输入第一个数字:')
num2=raw_input("请输入第二个数字:")
try:
    num1=int(num1)
    num2=int(num2)
    sum_demo=num1+num2
    print sum_demo
except Exception,e:
    print e

2.异常的种类

python中的异常种类非常多,每个异常专门用于处理某一类异常!!!

AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x IOError 输入/输出异常;基本上是无法打开文件

ImportError 无法引入模块或包;基本上是路径问题或名称错误

IndentationError 语法错误(的子类) ;代码没有正确对齐

IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5] KeyError 试图访问字典里不存在的键

KeyboardInterrupt Ctrl+C被按下 NameError 使用一个还未被赋予对象的变量

SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)

TypeError 传入对象类型与要求的不符合

UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它

ValueError 传入一个调用者不期望的值,即使值的类型是正确的

示例:

li=['yhj','dly']
try:
    print li[10]
except IndexError,ex:
    print "索引错误!"
except Exception,ex:
    print ex
dic_demo={'k1':'hehe',"k2":'heihei'}
try:
    print dic_demo['k5']
except KeyError,ex:
    print "键值错误!"
except Exception,ex:
    print ex
s='ttttt'
try:
    int_demo=int(s)
except ValueError,ex:
    print "值错误!"
except Exception,ex:
    print ex

3.异常的其他形式

try:
    #逻辑模块
    pass
except IndexError,e:
    #特定异常处理模块
    print e
except Exception,e:
    #通用异常处理模块
    print e
else:
    #逻辑模块没有发生异常后执行
    pass
finally:
    #无论什么情况,执行完逻辑模块后,都会执行
    pass

4.主动触发错误

try:
    raise Exception('自定义触发的错误!')
except Exception,e:
    print e

5.自定义错误

class AlexError(Exception):
    def __init__(self,msg=None):
        self.msg=msg
    def __str__(self):
        if self.msg:
            return self.msg
        else:
            return 'AAAAAA'


try:
    raise AlexError('Error Error')
except Exception,e:
    print e

6.断言

#断言不触发
assert 1==1
#断言触发
assert 1==2
原文地址:https://www.cnblogs.com/yanhongjun/p/5295192.html