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

1.      errors and exceptions

1.1.    syntax errors

>>> while True print('Hello world')

File "<stdin>", line 1

while True print('Hello world')

^

SyntaxError: invalid syntax

1.2.    异常处理

>>> while True:

...     try:

...         x = int(input("Please enter a number: "))

...         break

...     except ValueError:

...         print("Oops!  That was no valid number.  Try again...")

...

try语句工作原理:

  1. 首先,执行try和except之间的语句;
  2. 如果没有异常出现,except语句后的内容不执行,try语句执行结束;
  3. 如果在执行第一步时出现异常,剩余语句将跳过;如果抛出的异常类型与except后的关键字匹配,except部分语句执行;
  4. 如果出现异常但不匹配except给出的关键字类型,except后的语句将跳过,异常被抛给更外围的try语句,如果没有任何try语句捕获该异常,则输出缺省的出错信息。

一个try可以有多个except部分。

... except (RuntimeError, TypeError, NameError):

...     pass

更好的写法,最后一个except语句最好不带异常名,这样它可以处理所有的异常信息。

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

else语句,如果没有异常则执行此语句。

for arg in sys.argv[1:]:

try:

f = open(arg, 'r')

except OSError:

print('cannot open', arg)

else:

print(arg, 'has', len(f.readlines()), 'lines')

f.close()

try-finally语句,无论是否有异常,都将执行该语句。

try:

<语句>

finally:

<语句>    #退出try时总会执行

raise

except语句可以在异常名后指定一个变量,这个变量与一个异常实例绑定,参数存于instance.args

>>> try:

...     raise Exception('spam', 'eggs')

... except Exception as inst:

...     print(type(inst))    # the exception instance

...     print(inst.args)     # arguments stored in .args

...     print(inst)          # __str__ allows args to be printed directly,

...                          # but may be overridden in exception subclasses

...     x, y = inst.args     # unpack args

...     print('x =', x)

...     print('y =', y)

...

<class 'Exception'>

('spam', 'eggs')

('spam', 'eggs')

x = spam

y = eggs

1.3.    raising exceptions

raise语句可以触发一个异常。

raise [Exception [, args [, traceback]]]

>>> raise NameError('HiThere')

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: HiThere

1.4.    自定义异常

通过创建新的异常类,用户可以定义自己的异常类。一般情况下从Exception类直接或间接派生类。

异常类和其它类在本质上没什么不同,但一般只用异常类提供异常信息。

1.5.    异常清理

try…finally语句可以实现异常清理功能。

>>> def divide(x, y):

...     try:

...         result = x / y

...     except ZeroDivisionError:

...         print("division by zero!")

...     else:

...         print("result is", result)

...     finally:

...         print("executing finally clause")

...

>>> divide(2, 1)

result is 2.0

executing finally clause

>>> divide(2, 0)

division by zero!

executing finally clause

>>> divide("2", "1")

executing finally clause

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "<stdin>", line 3, in divide

TypeError: unsupported operand type(s) for /: 'str' and 'str'

1.6.    预定义清理操作

部分对象定义了标准清理操作,当该对象不在使用时执行,不论对该对象的操作成功与否。

典型的是文件打开和关闭,在这种情况下通常使用with语句。

with open("myfile.txt") as f:

for line in f:

print(line, end="")

笔记-python-tutorial-8.errors and exceptions的更多相关文章

  1. 《The Python Tutorial》——Errors and Exceptions 阅读笔记

    Errors and Exceptions 官方文档:https://docs.python.org/3.5/tutorial/errors.html python中所有的异常都继承自BaseExce ...

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

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

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

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

  4. Python Tutorial笔记

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

  5. 笔记-python lib-pymongo

    笔记-python lib-pymongo 1.      开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...

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

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

  7. [Notes] Learn Python2.7 From Python Tutorial

    I have planed to learn Python for many times. I have started to learn Python for many times . Howeve ...

  8. Python Tutorial 学习(六)--Modules

    6. Modules 当你退出Python的shell模式然后又重新进入的时候,之前定义的变量,函数等都会没有了. 因此, 推荐的做法是将这些东西写入文件,并在适当的时候调用获取他们. 这就是为人所知 ...

  9. Handling Errors and Exceptions

    http://delphi.about.com/od/objectpascalide/a/errorexception.htm Unfortunately, building applications ...

随机推荐

  1. path的join和resolve

    连接路径:path.join([path1][, path2][, ...]) path.join()方法可以连接任意多个路径字符串.要连接的多个路径可做为参数传入. path.join()方法在接边 ...

  2. js识别中英文字符的字节长度并进行裁切

    //调用方法,传入字符串和需要返回的字节长度即可function cutstr(str,len){ var str_length = 0; var str_len = 0; str_cut = new ...

  3. Android rxjava2的disposable

    rxjava+retrofit处理网络请求 在使用rxjava+retrofit处理网络请求的时候,一般会采用对观察者进行封装,实现代码复用和拓展.可以参考我的这篇文章:rxjava2+retrofi ...

  4. 阿里 EasyExcel 7 行代码优雅地实现 Excel 文件生成&下载功能

    欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 资深架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 个人网站: https://www.ex ...

  5. NopCommerce 3.80框架研究(二) MVC 表示层与数据验证

    表示层框架结构 /Views/Shared/_Root.Head.cshtml /Views/Shared/_Root.cshtml /Views/Shared/_ColumnsOne.cshtml ...

  6. 自行解决12306页面显示异常的问题(长城宽带下WWW。12306无法正常使用)

    前二天突然发现家里所用的长城宽带的www.12306.cn无法正常显示,点击余票查询或者车票预订均打不开,加载时间非常长,现象好似CSS等资源文件未载入成功(如图所示)更换chrome.firefox ...

  7. spring-autowire机制

    在xml配置文件中,autowire有5种类型,可以在<bean/>元素中使用autowire属性指定 模式                        说明 no            ...

  8. Linux运维工程师是什么鬼?

    第一部分:定义 运维工程师,字面理解运行维护. linux运维即linux运维工程师,集合网络.系统.数据库.开发.安全工作于一身的“复合性人才”.   除了传统IT运维部分,运维人员还是管理制度.规 ...

  9. CSS布局--垂直水平居中

    ···设置两个盒子 <div class="parent"> <div class="child"> </div></ ...

  10. Python 之继承

    概要 如果要修改现有类的行为,我们不必再从头建一个新的类,可以直接利用继承这一功能.下面将以实例相结合介绍继承的用法.   新建一个基类 代码如下: class Marvel(object): num ...