Errors and Exceptions

官方文档:https://docs.python.org/3.5/tutorial/errors.html

python中所有的异常都继承自BaseException类。

1.1 Syntax Errors

1.2 Exceptions

https://docs.python.org/3.5/library/exceptions.html

1.3 Handling Exception

使用try语句:

  1. >>> while True:
  2. ... try:
  3. ... x = int(input("Please enter a number: "))
  4. ... break
  5. ... except ValueError:
  6. ... print("Oops! That was no valid number. Try again...")
    except也可以使用元组:
  1. ... except (RuntimeError, TypeError, NameError):
  2. ... pass
    最后一个except可以省略异常名exception name,此时就跟通配符一样的作用(包含所有其他的异常)。
    基于此,可以在最后一句except中打印异常提示并可重新raise对应的异常:
  1. import sys
  2.  
  3. try:
  4. f = open('myfile.txt')
  5. s = f.readline()
  6. i = int(s.strip())
  7. except OSError as err:
  8. print("OS error: {0}".format(err))
  9. except ValueError:
  10. print("Could not convert data to an integer.")
  11. except:
  12. print("Unexpected error:", sys.exc_info()[0])
  13. raise
    还可以在try...except语句后使用else语句,适用于try后没发生相应异常又需要继续完成某种操作的情况:
  1. for arg in sys.argv[1:]:
  2. try:
  3. f = open(arg, 'r')
  4. except IOError:
  5. print('cannot open', arg)
  6. else:
  7. print(arg, 'has', len(f.readlines()), 'lines')
  8. f.close()
    异常handler不仅能够捕捉try语句中的异常,也可以捕捉try语句内被调用函数的异常(嵌套的非直接调用的函数产生的异常也行):
  1. >>> def this_fails():
  2. ... x = 1/0
  3. ...
  4. >>> try:
  5. ... this_fails()
  6. ... except ZeroDivisionError as err:
  7. ... print('Handling run-time error:', err)
  8. ...
  9. Handling run-time error: division by zero

1.4 Raising Exceptions

raise语句可以人为的让某个异常"发生":

  1. >>> raise NameError('HiThere')
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. NameError: HiThere
  5.  
  6. raise的参数只有一个,即为一个异常的实例名或异常类名(当然,这个异常也是继承自Exception类的),
    其实,当一个异常类被raise的时候,会自动调用它的构造函数“悄悄的”进行实例化:
  1. raise ValueError # shorthand for 'raise ValueError()'

1.5 User-defined Exception

  1. 所有异常类都继承自Exception类。
    通常的做法是先建立一个继承自ExceptionEroor,再根据不同的异常建立不同的异常类(继承Eroor):
  1. class Error(Exception):
  2. """Base class for exceptions in this module."""
  3. pass
  4.  
  5. class InputError(Error):
  6. """Exception raised for errors in the input.
  7.  
  8. Attributes:
  9. expression -- input expression in which the error occurred
  10. message -- explanation of the error
  11. """
  12.  
  13. def __init__(self, expression, message):
  14. self.expression = expression
  15. self.message = message
  16.  
  17. class TransitionError(Error):
  18. """Raised when an operation attempts a state transition that's not
  19. allowed.
  20.  
  21. Attributes:
  22. previous -- state at beginning of transition
  23. next -- attempted new state
  24. message -- explanation of why the specific transition is not allowed
  25. """
  26.  
  27. def __init__(self, previous, next, message):
  28. self.previous = previous
  29. self.next = next
  30. self.message = message

1.6 Defineing Clean-up Actions

  1. 使用finally语句:
  1. >>> try:
  2. ... raise KeyboardInterrupt
  3. ... finally:
  4. ... print('Goodbye, world!')
  5. ...
  6. Goodbye, world!
  7. KeyboardInterrupt
  8. Traceback (most recent call last):
  9. File "<stdin>", line 2, in <module>

1.7 Predefined Clean-up Actions

  1. with语句的使用:
  1. with open("myfile.txt") as f:
  2. for line in f:
  3. print(line, end="")
  1.  

《The Python Tutorial》——Errors and Exceptions 阅读笔记的更多相关文章

  1. [译]The Python Tutorial#8. Errors and Exceptions

    [译]The Python Tutorial#Errors and Exceptions 到现在为止都没有过多介绍错误信息,但是已经在一些示例中使用过错误信息.Python至少有两种类型的错误:语法错 ...

  2. Python Tutorial 学习(八)--Errors and Exceptions

    Python Tutorial 学习(八)--Errors and Exceptions恢复 Errors and Exceptions 错误与异常 此前,我们还没有开始着眼于错误信息.不过如果你是一 ...

  3. 《The Cg Tutorial》阅读笔记——动画 Animation

    这段时间阅读了英文版的NVidia官方的<The Cg Tutorial>,借此来学习基本的图形学知识和着色器编程. 在此做一个阅读笔记. 本文为大便一箩筐的原创内容,转载请注明出处,谢谢 ...

  4. 笔记-python-tutorial-8.errors and exceptions

    笔记-python-tutorial-8.errors and exceptions 1.      errors and exceptions 1.1.    syntax errors >& ...

  5. Python Tutorial笔记

    Python Tutorial笔记 Python入门指南 中文版及官方英文链接: Python入门指南 (3.5.2) http://www.pythondoc.com/pythontutorial3 ...

  6. python2.7官方文档阅读笔记

    官方地址:https://docs.python.org/2.7/tutorial/index.html 本笔记只记录本人不熟悉的知识点 The Python Tutorial Index 1 Whe ...

  7. [译]The Python Tutorial#4. More Control Flow Tools

    [译]The Python Tutorial#More Control Flow Tools 除了刚才介绍的while语句之外,Python也从其他语言借鉴了其他流程控制语句,并做了相应改变. 4.1 ...

  8. CI框架源码阅读笔记3 全局函数Common.php

    从本篇开始,将深入CI框架的内部,一步步去探索这个框架的实现.结构和设计. Common.php文件定义了一系列的全局函数(一般来说,全局函数具有最高的加载优先权,因此大多数的框架中BootStrap ...

  9. javascript高级程序设计阅读笔记(一)

    javascript高级程序设计阅读笔记(一) 工作之余开发些web应用作为兴趣,在交互方面需要掌握javascript和css.HTML5等技术,因此读书笔记是必要的. javascript简介 J ...

随机推荐

  1. LightOJ 1065 Island of Survival (概率DP?)

    题意:有 t 只老虎,d只鹿,还有一个人,每天都要有两个生物碰面,1.老虎和老虎碰面,两只老虎就会同归于尽 2.老虎和人碰面或者和鹿碰面,老虎都会吃掉对方 3.人和鹿碰面,人可以选择杀或者不杀该鹿4. ...

  2. 编写高质量代码改善C#程序的157个建议——建议27:在查询中使用Lambda表达式

    建议27:在查询中使用Lambda表达式 LINQ实际上是基于扩展方法和Lambda表达式的.任何LINQ查询都能通过扩展方法的方式来代替. var personWithCompanyList = f ...

  3. Spring源码研究:数据绑定

    在做Spring MVC时,我们只需用@Controllor来标记Controllor的bean,再用@RequestMapping("标记")来标记需要接受请求的方法,方法中第一 ...

  4. 关于.net DateTime 的一些事儿

    最近开发的过程中遇到一种情况,在.net 程序中获取的Datetime格式的时间,在存入SQL server中,毫秒部分丢失. 这个是个很奇怪的状况,因为在Debug的时候,Datetime的变量的确 ...

  5. C#中的枚举使用

    基本用法 默认从0开始分配各个枚举值对应的数字值 public enum VariableType { Type1, Type2 } 指定各个枚举值对应的数字值 public enum Variabl ...

  6. Linux中,关闭selinux

    首先我们可以用命令来查看selinux的状态getenforce 这个命令可以查看到selinux的状态,当前可以看到是关闭状态的. 还有一个命令也可以查看出selinux的状态.sestatus - ...

  7. CString、string、string.h的区别

    CString.string.string.h的区别   CString:CString是MFC或者ATL中的实现,是MFC里面封装的一个关于字符串处理的功能很强大的类,只有支持MFC的工程才能使用. ...

  8. luoguP2387 [NOI2014]魔法森林

    https://www.luogu.org/problemnew/show/P2387 考虑先将所有边按 a 值排序,依次加入每一条边,如果这条边的两个端点 ( l, r ) 之间的简单路径中 b 的 ...

  9. bzoj1565【NOI2009】植物大战僵尸(最小割)

    题目描述 Plants vs. Zombies(PVZ)是最近十分风靡的一款小游戏.Plants(植物)和Zombies(僵尸)是游戏的主角,其中Plants防守,而Zombies进攻.该款游戏包含多 ...

  10. model中的Meta类

    通过一个内嵌类 "class Meta" 给你的 model 定义元数据, 类似下面这样: class Foo(models.Model): bar = models.CharFi ...