异常

异常


  一般情况下,为了不使程序的bug直接了当的展现在用户面前,而是产生一个提示项,这个时候就需要用的异常处理。
####**语法:** ```python try: ... except Exception,ex: ... ------------------------------------ #例: my_dict={'1':1, '2':2} choice = input('>>>:').strip() try: print(my_dict[choice]) except KeyError: print ('no key %s'%choice) ------------------------------------- choice = '3' >>>:no key 3 ``` ####**常用异常:** ```python AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x IOError 输入/输出异常;基本上是无法打开文件 ImportError 无法引入模块或包;基本上是路径问题或名称错误 IndentationError 语法错误(的子类) ;代码没有正确对齐 IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5] KeyError 试图访问字典里不存在的键 KeyboardInterrupt Ctrl+C被按下 NameError 使用一个还未被赋予对象的变量 SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了) TypeError 传入对象类型与要求的不符合 UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量, 导致你以为正在访问它 ValueError 传入一个调用者不期望的值,即使值的类型是正确的 ```   异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。 ```python my_dict={'1':1, '2':2} choice = input('>>>:').strip() try: print(my_dict[choice]) except IndexError as e: print (e) ------------------------------------ 未捕获到异常,程序直接报错退出 ``` ####**捕获任意异常:**   当程序中需要捕获任意异常时,可以多次except可能出现的异常,也可以使用万能异常:Exception。 ```python '''多次except''' my_dict={'1':1, '2':2} choice = input('>>>:').strip() try: print(my_dict[choice])

except IndexError:
print ('no Index')
except ValueError:
print ('no Value')
except KeyError:
print ('no Key')

choice = '3'

:no key

'''Exception'''
my_dict={'1':1,
'2':2}
choice = input('>>>:').strip()

try:
print(my_dict[choice])
except Exception as e:
print (e)
print ('error')

choice = '3'

:3
:error

  通常情况下先定义其他的需要特殊处理或提醒的异常,最后用Exception来保证程序的正常运行。
```python
my_dict={'1':1,
         '2':2}
choice = input('>>>:').strip()

try:
    print(my_dict[choice])
except IndexError:
    print('Index Error')
except KeyError:
    print('KeyError')
except Exception:
    print ('error')
else:                   #无异常则执行
    print ('OK')
finally:               #不管有无异常最后都会执行
    print('hello world')

  需要注意的是,缩进类异常是无法捕获的。原因是因为代码本身因为格式错误无法被解释器解释,代码无法解释自然也就没办法进行捕获。

自定义异常:

class MyException(Exception)
    def __init__(self,msg)
        self.msg=msg
    #def __str__(self):   #Exception中定义了
        #return self.msg

try:
    raise MyException("连接错误")   #raise主动触发异常
except MyException as e:
    print (e)

断言:

  接下来的比较重要的代码执行依赖于前面的结果,通过断言来判断并进行下一步操作

a = 1
assert type(a) is int
print(a/2)
>>>0.5
---------------------------------------
assert type(a) is str
>>>:AssertionError
posted @ 2017-08-25 09:11  在下不想说  阅读(88)  评论(0编辑  收藏  举报