Python 异常 2018-08-01

  1. 例程:使用except并加上异常类型
# -*- coding: UTF-8 -*-                                          
try:
    fh = open("a.txt",'w')
    fh.write("This is a file for Exception test!")
except IOError:
    print "Error, file not found or access failure!"
else:
    print "Successful!"

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Successful!
helloworld@LG-virtual-machine:~/code$ cat a.txt 
This is a file for Exception test!helloworld@LG-virtu
  • 通过打开a.txt也能看到write()是不加换行符的
    1.2. 为了测试,我们先把a.txt得写权限给去掉,再重新执行以上代码,可以发现无法写入而产生的异常
chmod -w a.txt
helloworld@LG-virtual-machine:~/code$ python test.py 
Error, file not found or access failure!
  1. 使用异常而不带任何异常类型
try:
    正常的操作
   ......................
except:
    发生异常,执行这块代码
   ......................
else:
    如果没有异常执行这块代码
  1. 使用异常而带多种异常类型
try:
    正常的操作
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   发生以上多个异常中的一个,执行这块代码
   ......................
else:
    如果没有异常执行这块代码
  1. try...finally语句:无论是否发生异常都将执行最后的代码
# -*- coding: UTF-8 -*-                                          
try:
    fh = open("a.txt",'w')
    fh.write("This is a file for Exception test!")
finally:
    print "Error: File not found or access error"

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Error: File not found or access error
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    fh = open("a.txt",'w')
IOError: [Errno 13] Permission denied: 'a.txt'

helloworld@LG-virtual-machine:~/code$ chmod +w a.txt 
helloworld@LG-virtual-machine:~/code$ python test.py 
Error: File not found or access error
  1. 异常的参数:一个异常可以带上参数,可以作为输出时的异常参数
try:
    正常的操作
   ......................
except ExceptionType, Argument:
    你可以在这输出 Argument 的值...

实例:

# -*- coding: UTF-8 -*-                                          
def temp_convert(var):
    try:
        return int(var)
    except ValueError,Arg:
        print "参数不包含数字:",Arg

print temp_convert('xyz')

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
参数不包含数字: invalid literal for int() with base 10: 'xyz'
None
  1. 触发异常:

raise [Exception [, args [, traceback]]]
语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。

# -*- coding: UTF-8 -*-
def mye(level):
    if level < 1:
        raise Exception,"Invalid Error!" #触发异常后,后面的代码>将不会被执行

try:
    mye(0)
except Exception,err:
    print 1,err
else:
    print 2       

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
1 Invalid Error!
  1. 用户自定义的异常
    通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自Exception类,通过直接或间接的方式。
  • 以下为与RuntimeError相关的实例,实例中创建了一个类,基类为RuntimeError,用于在异常触发时输出更多的信息;
  • 在try语句块中,用户自定义的异常后执行except块语句,变量 e 是用于创建Networkerror类的实例。
# -*- coding: UTF-8 -*-
class NetworkError(RuntimeError):
    def __init__(self, arg):
        self.args = arg

try:
    raise NetworkError("Bad hostName")
except NetworkError,e:
    print e.args      

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
('B', 'a', 'd', ' ', 'h', 'o', 's', 't', 'N', 'a', 'm', 'e')

问题:为什么输出一个一个字母?以后再答

原文地址:https://www.cnblogs.com/qiulinzhang/p/9513576.html