首页 > 代码库 > python学习笔记7-异常处理

python学习笔记7-异常处理

1 写弄成了读

1
try: 2 fh = open("testfile", "r") 3 fh.write("This is my test file for exception handling!!") 4 except IOError: 5 print ("Error: can\‘t find file or read data") 6 7 else: 8 print ("Written content in the file successfully") 9 Error: cant find file or read data

2 异常触发

1 #异常触发
2 def functionName( level ):
3    if level < 1:
4       raise "Invalid level!", level
5       # The code below to this would not be executed
6       # if we raise the exception

3 自定义异常

1 #自定义异常
2 class Networkerror(RuntimeError):
3    def __init__(self, arg):
4       self.args = arg
5 
6 try:
7    raise Networkerror("Bad hostname")
8 except Networkerror,e:
9    print e.args

 

python学习笔记7-异常处理