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语句:

>>> while True:
... try:
... x = int(input("Please enter a number: "))
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
except也可以使用元组:
... except (RuntimeError, TypeError, NameError):
... pass
最后一个except可以省略异常名exception name,此时就跟通配符一样的作用(包含所有其他的异常)。
基于此,可以在最后一句except中打印异常提示并可重新raise对应的异常:
import sys

try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
还可以在try...except语句后使用else语句,适用于try后没发生相应异常又需要继续完成某种操作的情况:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
异常handler不仅能够捕捉try语句中的异常,也可以捕捉try语句内被调用函数的异常(嵌套的非直接调用的函数产生的异常也行):
>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print('Handling run-time error:', err)
...
Handling run-time error: division by zero

1.4 Raising Exceptions

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

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

1.5 User-defined Exception

所有异常类都继承自Exception类。
通常的做法是先建立一个继承自Exception的Eroor,再根据不同的异常建立不同的异常类(继承Eroor):
class Error(Exception):
"""Base class for exceptions in this module."""
pass class InputError(Error):
"""Exception raised for errors in the input. Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
""" def __init__(self, expression, message):
self.expression = expression
self.message = message class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed. Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
""" def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message

1.6 Defineing Clean-up Actions

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

1.7 Predefined Clean-up Actions

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

《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. Install zlib/libpng/jpeg/freetype/libgd/GD on Mavericks即mac10.9(转)

    转自:http://wangqinhu.com/install-gd-on-mavericks/ Various applications depend on library GD, however, ...

  2. IIS 身份验证

    IIS 支持以下身份验证模式: 匿名.如果不需要对客户端进行身份验证(或者使用自定义身份验证机制,如窗体身份验证),则可将 IIS 配置为允许匿名访问.在该事件中,IIS 创建一个 Windows 令 ...

  3. ASP.NET MVC 3 and the @helper syntax within Razor

    Friday, May 13, 2011 ASP.NET MVC 3 supports a new view-engine option called “Razor” (in addition to ...

  4. SQL之DCL

    DCL(Data Control Language)数据库控制语言  授权,角色控制等GRANT 授权REVOKE 取消授权 1)授权命令 grant,语法格式(SQL语句不区分大小写):Grant  ...

  5. Linux下的多线程下载工具mwget

    之前在做项目的时候,遇到一个难题,需要一个多线程下载器,于是阴差阳错的看到了这款工具--mwget,之所以是阴差阳错,是因为mwget的多线程下载功能,并不是我们想要的多线程. wget大家都知道吧, ...

  6. MongoDB整理笔记の新增Shard Server

    1.启动一个新Shard Server 进程 [root@localhost ~]# mkdir /data/shard/s2 [root@localhost ~]# /Apps/mongo/bin/ ...

  7. HTML5+CSS3网站设计教程 (张晓景,胡克) [iso]

    <HTML5+CSS3网站设计教程>系统地讲解了CSS的基础理论和实际运用技术,并结合多个案例讲解了采用CSS与层布局相结合制作网页的方法,在详细讲解各个案例的制作中,不仅介绍了CSS样式 ...

  8. Log--事务日志

    由于日志是顺序写入,而修改数据分散在数据库各个页面,属于随机写入,而磁盘顺序写入速度远高于随机写入,因此主流数据库都采用预写日志的方式来确保数据完整性 1.日志记录的是数据的变化而不是引发数据的操作2 ...

  9. 將sql server 2008R2 Max memory 意外設為0

    做sql server 內存Max memory 設定時大意,誤把最大值設為0,怎麼著都連不上DataBase,哪真叫個急呀,最後還是看到一條文命令把救回來了,其它很簡單急的時候就是沒想出來. 1.暫 ...

  10. Window 7 Professional 多语言设置

    1. 正常情况下,WINDOW系统只提供企业和旗舰版的语言切换的界面设置,其他版本没有. 2. 首先下载语言包,然后解压待用. 3. 以管理员身份运行命令窗口,如下输入: 4. 上面完成后,下载 ht ...