youbo1 发表于 2015-12-2 10:17:44

python学习笔记十:异常

一、语法



#!/usr/bin/python
filename='hello'
#try except finally demo
try:
open('abc.txt')
print hello
except IOError,msg:
print 'the file not exist'
except NameError,msg:
print 'hello not defined'
finally:
print 'end'
#throw exception
if filename == "hello":
raise TypeError('nothing')
二、常见异常类型
  1、AssertionError:assert语句失败
  2、AttributeError:试图访问一个对象没有的属性
  3、IOError:输入输出异常,基本是无法打开文件
  4、ImportError:无法引入模块或者包,基本是路径问题
  5、IndentationError:语法错误,代码没有正确对齐
  6、IndexError:下标索引超出序列边界
  7、KeyError:试图访问你字典里不存在的键
  8、KeyboardInterrupt:Ctrl+C被按下
  9、NameError:使用一个还声明的变量
  10、SyntaxError:代码逻辑语法出错,不能执行
  12、TypeError:传入的对象类型与要求不符
  13、UnboundLocalError:试图问一个还未设置的全局变量,基本上是由于另有一个同名的全局变量
  14、ValueError:传入一个不被期望的值,即使类型正确
页: [1]
查看完整版本: python学习笔记十:异常