zoukankan      html  css  js  c++  java
  • 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')
    

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

  • 相关阅读:
    第三方驱动备份与还原
    Greenplum 解决 gpstop -u 指令报错
    yum安装(卸载)本地rpm包的方法(卸载本地安装的greenplum 5.19.rpm)
    Java JUC(java.util.concurrent工具包)
    netty 详解(八)基于 Netty 模拟实现 RPC
    netty 详解(七)netty 自定义协议解决 TCP 粘包和拆包
    netty 详解(六)netty 自定义编码解码器
    netty 详解(五)netty 使用 protobuf 序列化
    netty 详解(四)netty 开发 WebSocket 长连接程序
    netty 详解(三)netty 心跳检测机制案例
  • 原文地址:https://www.cnblogs.com/qiulinzhang/p/9513576.html
Copyright © 2011-2022 走看看