异常

作者: endian | 来源:发表于2018-01-22 17:06 被阅读0次

    错误


    • 例如

        >>> Print('fdsa');
        Traceback (most recent call last):
          File "<pyshell#0>", line 1, in <module>
        Print('fdsa');
        NameError: name 'Print' is not defined
      
      • NameError被抛出,同时Python还会打印出检测到的错误发生的位置。着就是一个错误处理器(Error Handler)为这个错误所做的事情

    异常


    • 输入以下代码,按ctrl+d

        >>> s=input("input ----->");
        input ----->
        Traceback (most recent call last):
          File "<pyshell#1>", line 1, in <module>
        s=input("input ----->");
        EOFError: EOF when reading a line
        >>> 
      

    处理异常


    • 我们通过使用try...except来处理异常情况,一般来说我们会把通常的语句放在try代码块中,将我们的错误处理器代码放置在except代码块

    • 案例:

        try: 
            text = input("Enter something-->");
        except EOFError:
            print('Why did you do an EOFError on me');
        except KeyboardInterrupt:
            print('You cancelled the operation.');
        else:
            print('You Entered {}'.format(text));
      

    抛出异常


    • 可以通过raise语句来引发一次异常,具体方法是:

      • 提供错误名或异常名
      • 抛出异常的对象
    • 你能够引发的错误或异常必须是直接或间接从属于Exception(异常)类的派生类

    • 案例:

        class ShortInputException(Exception):
            def __init__(self,length,atLeast):
                Exception.__init__(self);
                self.length=length;
                self.atLeast = atLeast;
        
        try:
            text = input("please Enter sth--->");
            if len(text) <3:
                raise ShortInputException(len(text),3);
        except EOFError:
            print('Why did you do an EOFError on me');
        except ShortInputException as ex:
            print('ShortInputException:The input was '+
            '{0}long,expected at least{1}'.format(ex.length,ex.atLeast));
        else:
            print('No exception was raised.');
      
      • warning:我们在except字句中,提及了错误类,将该类存储as(为)相应的错误名或异常名ex;

    Try...Finally

    • 无论是否发生异常,都可以用finally

    • 案例:

        import sys;
        import time;
        f = None;
        try:
            f = open("poem.txt");
            
            while True:
                line = f.readline();
                if len(line)==0:
                    break;
                print(line,end='');
                sys.stdout.flush();
                print('Press ctrl+c now');
                #为了确保它能运行一段时间
                time.sleep(2);
        except IOError:
            print('Could not find file poem.txt');
        except KeyboardInterrupt:
            print('!! You cancelled the reading from the file.');
        finally:
            if f:
                f.close();
            print("(Cleaning up:Closed the file)");
      

    with语句


    • 在try块中获取资源,然后再finally块中释放资源是一种常见的模式。因此还有一个with语句使得这一过程可以以一种干净的姿态得以完成

    • 案例:

        with open('poem.txt') as f:
            for line in f:
                print(line,end='');

    相关文章

      网友评论

          本文标题:异常

          本文链接:https://www.haomeiwen.com/subject/bufraxtx.html