笔记-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. TemplateBinding与Binding区别,以及WPF自定义控件开发的遭遇

    在上一次的文章WPF OnApplyTemplate 不执行 或者执行滞后的疑惑谈到怎么正确的开发自定义控件,我们控件的样式中,属性的绑定一般都是用TemplateBinding来完成,如下一个基本的 ...

  2. <Android 应用 之路> 天气预报(四)

    前言 第二次尝试完成天气预报应用,与上次不同的是,个人感觉这次的Ui不那么丑陋,整体的实用性和界面效果,用户体验相较上一次有所提升,但是还是有很多地方需要完善. 这次使用到的内容比较丰富,包括聚合数据 ...

  3. System Center Configuration Manager 2016 域准备篇(Part1)

    本系列指南如何从Microsoft安装最新的Configuration Manager基准版本.较新的可用基准版本System Center Configuration Manager(当前分支)版本 ...

  4. 面试官:自己搭建过vue开发环境吗?

    开篇 前段时间,看到群里一些小伙伴面试的时候被面试官问到这类题目.平时大家开发vue项目的时候,相信大部分人都是使用 vue-cli脚手架生成的项目架构,然后 npm run install 安装依赖 ...

  5. hdu-1166 敌兵布阵---树状数组模板

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1166 题目大意: 维护动态的区间和,单点更新,就是模板题 #include<iostream& ...

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

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

  7. JS判断单、多张图片加载完成

    转:http://www.daqianduan.com/6419.html 试想,如果模板中有图片,此时如何判断图片是否加载完成? 在此之前来了解一下jquery的ready与window.onloa ...

  8. 说说qwerty、dvorak、colemak三种键盘布局

    [qwerty布局] qwerty布局大家应该都很熟悉了,全世界最普及的键盘布局. 截止到去年接触并使用dvorak布局之前,我使用了十几年qwerty布局,在http://speedtest.10f ...

  9. kubernetes-配置管理(十一)

    Secret https://kubernetes.io/docs/concepts/configuration/secret/ Secret解决了密码.token.密钥等敏感数据的配置问题,而不需要 ...

  10. javaweb基础(26)_jsp标签库开发二

    一.JspFragment类介绍 javax.servlet.jsp.tagext.JspFragment类是在JSP2.0中定义的,它的实例对象代表JSP页面中的一段符合JSP语法规范的JSP片段, ...