Python错误和异常

错误

从软件方面来说,错误是语法或是逻辑上的
语法错误指示软件的结构上有错误,导致不能被解释器解释或编译器无法编译,这些错误必须在程序执行前纠正
逻辑错误可能是由于不完整或是不合法的输入所致
还可能是逻辑无法生成,计算,或是输出结果需要的过程无法执行
 
简单的语法错误
>>> 
KeyboardInterrupt
>>> abcd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'abcd' is not defined
>>> pass = 'qbcd'
  File "<stdin>", line 1
    pass = 'qbcd'
         ^
SyntaxError: invalid syntax

异常

当python检测到一个错误时,解释器就会指出当前流已经无法继续执行下去,这时候出现了异常
异常是因为程序出现了错误而在正常控制流以外采取的行为
这个行为又分为两个阶段,首先是引起异常发生的错误,然后是检测(和采取可能的措施)阶段
当程序运行时,因为遇到了未解的错误而导致终止运行,便会出现traceback消息,打印异常
异常
描述
NameError
未声明/初始化对象
IndexError
序列中没有此索引
SyntaxError
语法错误
KeyboardInterruupt
用户中断执行
EOFError
没有内建输入,达到EOF标记
IOError
输入/输出操作失败

try-except语句

定义了进行异常监控的一段代码,并且提供了处理异常的机制
语法:
try
 try_suite#监控这里的异常
except Exception【,reason】
 except_suite#异常处理代码
>>> try:
...     f = open('foo.txt')
... 
  File "<stdin>", line 3
    
    ^
SyntaxError: invalid syntax
>>> try:
...     f = open('foo.txt')
... except IOError:
...     print "No such file"
... 
No such file
#!/usr/bin/env python

import time

for i in range(1,11):
    print i
    try:
        time.sleep(0.5)
    except KeyboardInterrupt:
        pass

print 'done'

[root@bogon untitled10]# ./Ptime.py 
1
2
3
4
^C5
^C6
^C7
8
9
10
done

捕获所有异常

#!/usr/bin/env python

num = ''
result = ''

try:
    num = int(raw_input("please input some number:>"))
    result = 100/num
except:
    print "some error"

print result

[root@bogon untitled10]# ./Aerror.py 
please input some number:>0
some error

[root@bogon untitled10]# ./Aerror.py 
please input some number:>a
some error

[root@bogon untitled10]# ./Aerror.py 
please input some number:>^Csome error

[root@bogon untitled10]# ./Aerror.py 
please input some number:>some error

改进代码

#!/usr/bin/env python

num = ''
result = ''

try:
    num = int(raw_input("please input some number:>"))
    result = 100/num
except (KeyboardInterrupt,EOFError):
    print "
user cancelled"
except (ValueError,ZeroDivisionError),e:
    print "
Error" ,e
print result



#!/usr/bin/env python

num = ''
result = ''

try:
    num = int(raw_input("please input some number:>"))
    result = 100/num
except (KeyboardInterrupt,EOFError):
    print "
user cancelled"
except (ValueError,ZeroDivisionError),e:
    print "
Error" ,e
print result

raise,自定义异常

>>> raise aaa
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'aaa' is not defined
>>> raise ValueError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError
>>> raise ValueError ,'some error'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: some error
#!/usr/bin/env python

def set_age(name,age):
    if age < 1 or age > 150:
        raise ValueError,"age out of range"
    print "%s is %s year old" % (name,age)

set_age('bob',-1)


/usr/bin/python2.6 /root/PycharmProjects/untitled10/Prasie.py
Traceback (most recent call last):
  File "/root/PycharmProjects/untitled10/Prasie.py", line 8, in <module>
    set_age('bob',-1)
  File "/root/PycharmProjects/untitled10/Prasie.py", line 5, in set_age
    raise ValueError,"age out of range"
ValueError: age out of range

Process finished with exit code 1

断言

断言是依据必须等价于布尔值为真的判定,此外发生异常也意味着表达式为假
#!/usr/bin/env python

def set_age(name,age):
    if age < 1 or age > 150:
        raise ValueError,"age out of range"
    print "%s is %s year old" % (name,age)

def set_age2(name,age):
    assert 0 < age <= 150,'Age out of range'
    print "%s is %s year old" % (name,age)

set_age('bob',20)
set_age2('tom',200)



/usr/bin/python2.6 /root/PycharmProjects/untitled10/Prasie.py
bob is 20 year old
Traceback (most recent call last):
  File "/root/PycharmProjects/untitled10/Prasie.py", line 13, in <module>
    set_age2('tom',200)
  File "/root/PycharmProjects/untitled10/Prasie.py", line 9, in set_age2
    assert 0 < age <= 150,'Age out of range'
AssertionError: Age out of range

Process finished with exit code 1
原文地址:https://www.cnblogs.com/weiwenbo/p/6626883.html