Python异常处理try...except...finally raise assert
2016-09-01 09:38
776 查看
异常处理:
try ...except try代码块放置容易发生异常的语句:except代码块放置处理异常的语句
try ...except...finally finally代码快是任何时候都会执行的;通常用于关闭系统的资源
raise 抛出异常;
自定义异常:
必须继承于Exception类
类名以Error结尾
自定义异常使用raise语句引发,而且只能通过手工引发:
Python pass 语句
Python pass是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句。
assert:语句用于测试某个条件表达式为真,即认为测的表达式永远为真,如果断言失败,会引发AssertionError异常
异常信息:
str = 'hello'
try ...except try代码块放置容易发生异常的语句:except代码块放置处理异常的语句
try ...except...finally finally代码快是任何时候都会执行的;通常用于关闭系统的资源
try: f = open('db100.txt','r') try: a = f.write('aa') print a except: print 'write error' finally: f.close() print 'close file' except: print 'open error' 输出: write error close file
raise 抛出异常;
def reporterror(x): if x == None: raise NameError print x try: reporterror(None) except NameError: print 'x == None' #输出: x == None
自定义异常:
必须继承于Exception类
类名以Error结尾
自定义异常使用raise语句引发,而且只能通过手工引发:
Python pass 语句
Python pass是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句。
class MyError(Exception): pass def reporterror(x): if x == None: raise MyError() print x try: reporterror(None) except MyError,error: print 'x == None' #输出: x == None --------------------------------------
assert:语句用于测试某个条件表达式为真,即认为测的表达式永远为真,如果断言失败,会引发AssertionError异常
str = 'hello' try: #x = 10/0 assert len(str) == 3 except AssertionError,x: print 'assert error',x 输出: assert error
异常信息:
str = 'hello'
try: x = 10/0 assert len(str) == 3 except AssertionError,x: print 'assert error',x except Exception ,ex: print ex 输出: integer division or modulo by zero
相关文章推荐
- Python异常处理try...except...finally raise assert
- python异常处理try,except,else,finally,raise
- 【python学习笔记】Python异常处理raise、try...except、断言assert
- Python学习笔记之错误处理(关键词:错误处理、异常机制、try、except、else、finally、raise)
- Python异常处理——try...except、主动引发异常(raise)、断言(assert)
- python异常处理try,except,else,finally,raise
- python中的异常处理:try...except...else...finally语句
- python 错误处理:try..except..finally / logging / raise
- (Python)异常处理try...except、raise
- python 异常处理-try-except-else-finally
- Python异常处理try...except、raise
- Python中的异常处理: try-except-else-finally
- (Python)异常处理try...except、raise
- (Python)异常处理try...except、raise
- Python异常处理try...except、raise
- 【】Python】异常处理try...except、raise
- (Python)异常处理try...except、raise
- Python中异常处理简单示例(try,except,finally)
- Python_异常处理try...except、raise
- (Python)异常处理try...except、raise