Error handling
try
,except
,finally
The statement in try is executed first, and if an error occurs, it is caught by except. Otherwise, an else statement is executed, and finally statement is executed
try:
print('try... ')
r = 10 / int('2')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error! ')
finally:
print('finally... ')
print('END')
Copy the code
try...
result: 5.0
no error!
finally...
END
Copy the code
An exception is thrown
IOError: input/output exceptions; ImportError: Unable to import modules or packages; IndentationError: IndentationError; KeyError: attempts to access a key that does not exist in the dictionary AttributeError: attempts to access an attribute that does not exist in the object TypeError: type mismatch ValueError: Passing in a value that the caller does not expect, even if the value is of the correct type
Exceptions themselves are also classes
class FooError(ValueError) :# define exception
pass
def foo(s) :
n = int(s)
if n==0:
raise FooError('Invalid value: %s' % s)Throw an exception
return 10 / n
foo('0')
Copy the code
--------------------------------------------------------------------------- FooError Traceback (most recent call last) <ipython-input-10-0c3ece3b8a4a> in <module> 8 return 10 / n 9 ---> 10 foo('0') <ipython-input-10-0c3ece3b8a4a> in foo(s) 5 n= int(s) 6 if n==0: ----> 7 Raise FooError(' Invalid value: %s' %s)# raise exception 8 return 10 / n 9 FooError: invalid value: 0Copy the code
Using Rasie without any content directly throws an error
def foo(s) :
n = int(s)
if n==0:
raise ValueError('invalid value: %s' % s)
return 10 / n
def bar() :
try:
foo('0')
except ValueError as e:
print('ValueError! ')
raise Continue to throw the current error
bar()
Copy the code
ValueError! --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-11-2304461f3f2b> in <module> 12 raise # continue to raise the current error 13 --> 14 bar() <ipython-input-11-2304461f3f2b> in bar() 7 def bar(): 8 try: ----> 9 foo('0') 10 except ValueError as e: 11 print('ValueError! ') <ipython-input-11-2304461f3f2b> in foo(s) 2 n = int(s) 3 if n==0: ----> 4 raise ValueError('invalid value: %s' % s) 5 return 10 / n 6 ValueError: invalid value: 0Copy the code
assert
assertions
An assert condition that throws information carried by an AssertionError exception
eg:assert n! =0,’n is zero! ‘
You can turn off the assertion switch when running python files python -o xxx.py, which is the capital letter O, not the number 0
def foo(s) :
n = int(s)
assertn ! =0.'n is zero! '
return 10 / n
foo('0')
Copy the code
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-24-1d060d98ffe3> in <module> 4 return 10 / n 5 ----> 6 foo('0') <ipython-input-24-1d060d98ffe3> in foo(s) 1 def foo(s): 2 n = int(s) ----> 3 assert n ! = 0, 'n is zero! ' 4 return 10 / n 5 AssertionError: n is zero!Copy the code
logging
The module
It only works when the file is running. Interactive mode is not displayed
import loggingImport the logging package
logging.basicConfig(level=logging.INFO)Set the log output level to INFO
logging.info('123456')# output
Copy the code
INFO:root:n = 0
Traceback (most recent call last):
File "test.py", line 7, in <module>
print(10 / n)
ZeroDivisionError: division by zero
Copy the code
Unit testing
Start by writing a class to be tested
class Dict(dict) :
def __init__(self, **kw) :
super().__init__(**kw)
def __getattr__(self, key) :
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value) :
self[key] = value
# It can be used as follows
d = Dict(a=1, b=2)
print(d['a'])
print(d.b)
Copy the code
1
2
Copy the code
Write unit test classes
import unittest Import the unit test module
class TestDict(unittest.TestCase) :Write a unittest class that inherits unittest.testcase
Write unit test methods that must begin with test
def test_init(self) :
d = Dict(a=1, b='test')
self.assertEqual(d.a, 1)#unittest.TestCase built-in assertion method
self.assertEqual(d.b, 'test')
self.assertTrue(isinstance(d, dict))
def test_key(self) :
d = Dict()
d['key'] = 'value'
self.assertEqual(d.key, 'value')
def test_attr(self) :
d = Dict()
d.key = 'value'
self.assertTrue('key' in d)
self.assertEqual(d['key'].'value')
def test_keyerror(self) :
d = Dict(a)with self.assertRaises(KeyError):#unittest.TestCase expects to raise KeyError
value = d['empty']
def test_attrerror(self) :
d = Dict(a)with self.assertRaises(AttributeError):#unittest.TestCase expects an AttributeError to be thrown
value = d.empty
Copy the code
Running unit tests
Method 1
Add it directly to the code
if __name__ == '__main__':
unittest.main()
Copy the code
Then run the file python xxx.py directly
Method 2
On the command line, type python -m unittest XXX, where XXX is the file name without the suffix py
Two special methods in unit testssetUp
withtearDown
Execute separately before and after each test method
For example, if the test method needs to connect to the database, you can open the database connection in the setUp method and close the database connection in the tearDown method
class TestDict1(unittest.TestCase) :
def setUp(self) :
print('setUp... ')
def tearDown(self) :
print('tearDown... ')
Copy the code
Copy the code