14Python中的异常
来源:互联网 发布:mac qq 编辑:程序博客网 时间:2024/06/07 04:30
# -*- coding: UTF-8 -*-# 1.如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),# 然后控制流通过整个try语句。try: fn = open("testfile", "r");except IOError: print "读取失败"else: print "读取成功" # 没有异常发生则执行else,否则执行except。 fn.close()# 2.try-except语句捕获所有发生的异常try: fn = open("testfile", "r")except: print "failed"else: pass# 3.try-finally 语句无论是否发生异常都将执行最后的代码。try: fh = open("test", "w") try: fh.read(10); finally: print "关闭文件" fh.close();except IOError: print "failed to open."# 4.raise抛出异常def fun(level): if level < 1: raise Exception("Invalid level", level) # 抛出异常try: fun(-1)except Exception as e: print "invalid", eelse: print "valid"# 5.自定义异常。# 以下为与RuntimeError相关的实例,实例中创建了一个类,基类为RuntimeError,# 用于在异常触发时输出更多的信息。class NetworkError(RuntimeError): def __init__(self, arg): # 构造函数。 self.args = argtry: raise NetworkError("bad hostname")except NetworkError, e: print e.args
阅读全文
0 0
- 14Python中的异常
- Python中的异常类型
- Python中的一些异常
- python中的异常
- python 中的异常
- Python中的异常类型
- Python中的异常类型
- Python中的异常处理
- python中的异常总结
- python中的异常处理
- Python中的异常
- python中的异常处理
- python中的异常处理
- python中的异常
- python 中的异常处理
- Python中的异常类型
- python中的异常
- python中的异常
- AssetBundle
- 13Python中的文件操作
- Leetcode 594 Longest Harmonious Subsequence
- HTTPS学习
- 【1565】十进制数转二进制从低位到高位输出
- 14Python中的异常
- MYSQL:INNER JOIN的用法
- 欢迎使用CSDN-markdown编辑器
- PAT(Basic Level)Practise-----1001
- Leetcode 447 Number of Boomerangs
- pid max导致fork: Cannot allocate memory 的分析及解决办法
- hbase 源代码解析(23)truncate 和truncate_preserve流程分析
- lua解决八皇后问题
- Linux系统网卡名称固化