异常

作者: 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='');

相关文章

  • 异常和模块

    异常 目标 了解异常 捕获异常 异常的else 异常finally 异常的传递 自定义异常 一. 了解异常 当检测...

  • python多线程

    异常基础知识 -异常简介: 运行时错误 -异常类: 异常数据 异常名称,异常数据,异常类型 -自定义异常 clas...

  • dart 异常

    dart中的异常 异常处理 抛出异常 异常捕获

  • Java基础之异常

    Java基础之异常 目录 异常简单介绍 ThrowableErrorException 异常分类 如何处理异常异常...

  • python核心编程-错误与异常

    本章主题:什么是异常Python中的异常探测和处理异常上下文管理引发异常断言标准异常创建异常相关模块 什么是异常 ...

  • motan(RPC)系统梳理知识点

    异常分类: 业务异常(bizException) 服务异常(serviceException) 框架异常(fram...

  • 异常

    Java异常体系 异常的分类 Java的异常分为两大类:Checked异常和Runtime异常(运行时异常)。所有...

  • 从零构架个人博客网站(二)-全局异常处理

    中间件的异常 全局异常中间件全局异常监听定义异常的返回结果定义常见的异常状态开发环境 异常查看 对于异常,我们可以...

  • Node.js异常处理

    Node.js异常分类: 变量异常 函数异常 调用异常 变量异常 未定义变量 未包含对象 变量类型错误 函数异常 ...

  • python 异常

    异常 目标 异常的概念 捕获异常 异常的传递 抛出异常 01. 异常的概念 程序在运行时,如果 Python 解释...

网友评论

      本文标题:异常

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