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')
    

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

  • 相关阅读:
    CSS规范
    CSS规范
    CSS规范
    CSS function--(来自网易)
    CSS reset--(来自网易)
    js截取图片上传(仅原理)----闲的无聊了代码就不共享了!写的难看,不好意思给你们看了(囧)
    作业:JavaScript(数组篇-poker)给我的徒弟出个题。。。记得早点写完,然后大家3人可以早点打牌了
    BAT及各大互联网公司2014前端笔试面试题--JavaScript篇(昨天某个群友表示写的简单了点,然后我无情的把他的抄了一遍)
    BAT及各大互联网公司2014前端笔试面试题--Html,Css篇(昨天有个群友表示写的简单了点,然后我无情的把他的抄了一遍)
    本日吐槽!“人傻钱多”的P2P公司是否是程序员的合适选择(群聊天记录的娱乐)
  • 原文地址:https://www.cnblogs.com/qiulinzhang/p/9513576.html
Copyright © 2011-2022 走看看