1. 程式人生 > >python學習筆記7-異常處理

python學習筆記7-異常處理

exec blog span log exception pytho clas 處理 cep

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-異常處理