异常处理

 1 class MyException(Exception):
 2     """
 3     自定义异常,继承Exception
 4     """
 5     def __init__(self, msg):
 6         self.msg = msg
 7 
 8     def __str__(self):
 9         """
10         当实例化对象后,print对象将打印该值
11         """
12         return self.msg
13 
14 myexception = MyException
15 try:
16 
17     num1 = input("num1:")
18     num2 = input("num2")
19     num1 = int(num1)
20     num2 = int(num2)
21     result = num1 + num2
22     print(result)
23     raise myexception("yes. it's ok")
24 except ValueError as v:
25     print("value error", v)
26 except myexception as e:
27     print(e)
28 except KeyboardInterrupt:
29     print("上面无法抓住终止")
30 except InterruptedError:
31     print("test")
32 except SyntaxError:
33     print("该异常无法捕获")
34 except IndentationError:
35     print("该异常依然无法捕获")
36 except Exception:
37     print("no")
38 else:
39     print("一般测试用例,或者安装,可以使用,比如安装成功,没有错误")
40 finally:
41     print("不管前面什么错,最终都会执行这里,除了语法,缩进以外")

 

 

断言

 

断言一般用于条件匹配,如果条件不满足,则不会进行下去,除非刻意去捕获处理

1 a = ["1", "2", "3"]
2 filter_a = filter(lambda i: int(i) < 2, a)
3 print(list(filter_a))
4 try:
5     assert len(list(filter_a)) == len(a)
6     
7 except AssertionError:
8     print("条件不匹配,")

 

posted @ 2016-03-11 13:15  曾春云  阅读(187)  评论(0编辑  收藏  举报