代码改变世界

错误和异常86

2018-06-29 17:55  改改~_~  阅读(290)  评论(0编辑  收藏  举报
 1 # while True: print('Hello World!')
 2 print('异常有不同的类型,这些类型都作为信息的一部分打印出来:以下例子中的类型有ZeroDivisiongError,NameError和TypeError')
 3 # print(10*(1/0))
 4 
 5 # print(4+spam*3)
 6 
 7 # print('2'+2)
 8 
 9 print('Enter a number,if not give a exception')
10 while True:
11     try:
12         str = int(input('Please enter a number'))
13         # break
14     except ValueError:
15         print('Oops,That was no valid number .Try again ')
16 
17 print('except(RuntimeError,ValueError,TypeError,NameError)')
18 import sys
19 try:
20 
21     f = open('E:\\foo.txt')
22     s = f.readline()
23     i = int(s.strip())
24 except OSError as err:
25     print('OS error:{}'.format(err))
26 
27 except ValueError:
28     print('Could not conver a data to a integer.')
29 except:
30     print('Unexpected error:',sys.exc_info()[0])
31     raise
32 
33 print('example2----------------------------------------------------------')
34 import sys
35 for foo in sys.argv[1:]:
36     try:
37         f = open(foo,'r')
38     except IOError:
39         print('cannot open',foo)
40     else:
41         print(foo,'has',len(f.readlines()),'lines')
42         f.close()
43 
44 print('heheda-------------------------------------')
45 def this_fails():
46     x = 1/0
47 try:
48     this_fails()
49 except ZeroDivisionError as err:
50     print('Handling run-time error:',err)
51 
52 print('hehda-------------------------------------')
53 raise NameError('HiThere')
54 try:
55     raise NameError('HiThere')
56 except NameError:
57     print('An exception flew by!')
58     raise
59 
60 print('hehda----------------------------------------------')
61 class MyError(Exception):
62     def __init__(self,value):
63         self.value = value
64     def __str__(self):
65         return repr(self.value)
66 try:
67     raise MyError(2*2)
68 except MyError as e:
69     print('My exception occurred,value:'.format(e.value))
70 
71 print('hehda----------------------------------------------')
72 
73 
74 class MyError(Exception):
75     def __init__(self, value):
76         self.value = value
77 
78     def __str__(self):
79         return repr(self.value)
80 
81 try:
82     raise MyError(2 * 2)
83 except MyError as e:
84     print('My exception occurred,value:'.format(e.value))
85 
86 raise MyError('oops!')