pythonでの異常処理
14611 ワード
1、pythonでの例外の処理方法:
1 #encoding=utf-8
2
3 """
4 python ,
5 try:
6 " "
7 print "haha"
8 except:
9 " "
10 else:
11 " "
12 finally:
13 " try , "
14
15 :
16 1、 ;
17 2、 :
18 :except IOError:
19
20 """
21
22 a = [1, 2, 3, 4, 5, 6]
23
24 print a[4]
25
26 try:
27 print a[6]
28 except:
29 print u' '
30
31 print " "
32
33
34 try:
35 print a[6]
36 except:
37 print "huhu"
38 else:
39 print "hoho"
40 finally:
41 print "hehe"
42
43
44 import urllib
45 sth_url = "http://wsdfsdf"
46
47 try:
48 d = urllib.urlopen(sth_url)
49 except:
50 print " "
51 else:
52 content = d.read()
53 finally:
54 pass
55 #d.close()
56
57 """
58 note:
59 1、 try except
60 2、 python , ;
61 IOErro, IndexError
62 3、 :
63 import logging
64 logger = logging.getLogger()
65 #logfile = 'excetion_demo.log' #log
66 hdlr = logging.FileHandler('/tmp/sendlog.txt')
67 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
68 hdlr.setFormatter(formatter)
69 logger.addHandler(hdlr) #logging
70 logger.setLevel(logging.NOTSET)
71
72
73 import sys, logging
74 try:
75 d = urllib.urlopen("www.kdkdk.com")
76 except:
77 exc = sys.exc_info()
78 loggin.debug(exc[1]
79 print exc[1]
80 print exc
81 4、 ,assert
82 assert ," message"
83 assert 1>4, "expression Error"
84 , ;
85 """
86
87 """
88 with :
89 # , __enter__
90 # , __exit__
91
92 d = open('a', 'r')
93 d.read()
94 d.close()
95
96 with open('a', 'r') as d:
97 content = a.read()
98 """
99
100 #with :
101 class sth(object):
102 def __init__(self, xixi):
103 self.a = xixi
104
105 def __enter__(self):
106 print u' , '
107 return self.a
108
109 def __exit__(self, type, value, traceback):
110 print u' , '
111
112 with sth("gg") as s:
113 print s #s __enter__
114
115 """
116
117 """
118
119 class myException(Exception):
120 def __init__(self, error, msg):
121 self.args = (error, msg)
122 self.error = error
123 self.msg = msg
124
125 try:
126 raise myException(1, "my exception")
127 except Exception as e:
128 print str(e)