defdiv(a, b): try: print(a / b) #在try块中出现错误会直接去找except块,不执行try块中剩下代码 print(b) except ZeroDivisionError: #精准捕获后可自定义输出提示 print("Error: b should not be 0 !!") except Exception as e: #没有被捕获的异常全部在Exception中,这时最好将捕获到的信息输出提示 print("Unexpected Error: {}".format(e)) else: #如果没有异常会执行else语句 print('Run into else only when everything goes well') finally: #finally语句一定会被执行; 一般会用于最后释放资源(文件、网络连接) print('Always run into finally block.') print("END")
#Test1 div(2, 0) #输出 Error: b should not be 0 !! Always run into finally block. END
#Test2 div(2, 'bad type') #输出 Unexpected Error: unsupported operand type(s) for /: 'int'and'str' Always run into finally block. END
#Test3 div(1, 2) #输出 0.5 2 Run into else only when everything goes well Always run into finally block. END
#如果没有捕获异常,则由python解释器抛出的错误。错误一直向上抛,直至被解释器捕获 Traceback (most recent call last): File "/Users/peterson/PycharmProjects/LiaoxuefengLearn/test3.py", line 18, in <module> print(main(2, 0)) File "/Users/peterson/PycharmProjects/LiaoxuefengLearn/test3.py", line 14, in main return double(a, b) File "/Users/peterson/PycharmProjects/LiaoxuefengLearn/test3.py", line 10, in double return div(a, b) * 2 File "/Users/peterson/PycharmProjects/LiaoxuefengLearn/test3.py", line 6, in div return a/b ZeroDivisionError: division by zero
defmain(a, b): try: return double(a, b) except Exception as e: logging.exception(e) print("=" * 6, 'END', "=" * 6)
main(2, 0)
#输出(在没有触发程序中断的情况下并记录了log) ====== END ====== ERROR:root:division by zero Traceback (most recent call last): File "/Users/xxx/test3.py", line 16, in main return double(a, b) File "/Users/xxx/test3.py", line 11, in double return div(a, b) * 2 File "/Users/xxx/test3.py", line 7, in div return a/b ZeroDivisionError: division by zero
deferror(): raise MyError("This is an error raised by myself")
error()
#输出 Traceback (most recent call last): File "/Users/xxx/test3.py", line 12, in <module> error() File "/Users/xxx/test3.py", line 10, in error raise MyError("This is an error raised by myself") __main__.MyError: This is an error raised by myself
#输出 Traceback (most recent call last): File "/Users/xxx/test3.py", line 20, in <module> main(2, 0) File "/Users/xxx/test3.py", line 16, in main return double(a, b) File "/Users/xxx/test3.py", line 12, in double return div(a, b) * 2 File "/Users/xxx/test3.py", line 7, in div assert b != 0, 'b is zero!' AssertionError: b is zero! #断言在此
Process finished with exit code 1
关闭断言: python -O xx.py
1 2 3 4 5 6 7 8 9 10 11
>>> python3 -O test3.py Traceback (most recent call last): File "test3.py", line 20, in <module> main(2, 0) File "test3.py", line 16, in main return double(a, b) File "test3.py", line 12, in double return div(a, b) * 2 File "test3.py", line 8, in div return a/b ZeroDivisionError: division by zero #这样一来就忽略了所有 assert
#输出 INFO:root:b=0#日志输出在此 Traceback (most recent call last): File "/Users/xxx/test3.py", line 21, in <module> main(2, 0) File "/Users/xxx/test3.py", line 17, in main return double(a, b) File "/Users/xxx/test3.py", line 13, in double return div(a, b) * 2 File "/Users/xxx/test3.py", line 9, in div return a/b ZeroDivisionError: division by zero
deftest_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) # check that s.split fails when the separator is not a string with self.assertRaises(TypeError): #抛出一个特定异常 s.split(2)
""" This is the "example" module. The example module supplies one function, factorial(). For example, >>> factorial(5) 120 """
deffactorial(n): """Return the factorial of n, an exact integer >= 0. >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> factorial(30) 265252859812191058636308480000000 >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 Factorials of floats are OK, but the float must be an exact integer: >>> factorial(30.1) Traceback (most recent call last): ... ValueError: n must be exact integer >>> factorial(30.0) 265252859812191058636308480000000 It must also not be ridiculously large: >>> factorial(1e100) Traceback (most recent call last): ... OverflowError: n too large """
import math ifnot n >= 0: raise ValueError("n must be >= 0") if math.floor(n) != n: raise ValueError("n must be exact integer") if n+1 == n: # catch a value like 1e300 raise OverflowError("n too large") result = 1 factor = 2 while factor <= n: result *= factor factor += 1 return result
if __name__ == "__main__": import doctest doctest.testmod()
#输出 >>> python test4.py -v #写在注释中的示例都会被测试 Trying: factorial(5) Expecting: 120 ok Trying: [factorial(n) for n inrange(6)] Expecting: [1, 1, 2, 6, 24, 120] ok Trying: factorial(30) Expecting: 265252859812191058636308480000000 ok Trying: factorial(-1) Expecting: Traceback (most recent call last): ... ValueError: n must be >= 0 ok Trying: factorial(30.1) Expecting: Traceback (most recent call last): ... ValueError: n must be exact integer ok Trying: factorial(30.0) Expecting: 265252859812191058636308480000000 ok Trying: factorial(1e100) Expecting: Traceback (most recent call last): ... OverflowError: n too large ok 2 items passed all tests: 1 tests in __main__ 6 tests in __main__.factorial 7 tests in2 items. 7 passed and0 failed. Test passed.