how to handle Exceptions: tests and solutions¶
tests¶
the code in exceptions/tests/test_exceptions.py from how to handle Exceptions in programs
1import src.exceptions
2import unittest
3
4
5class TestExceptions(unittest.TestCase):
6
7 def test_catching_module_not_found_error_in_tests(self):
8 with self.assertRaises(ModuleNotFoundError):
9 import does_not_exist
10
11 def test_catching_name_error_in_tests(self):
12 with self.assertRaises(NameError):
13 does_not_exist
14
15 def test_catching_attribute_error_in_tests(self):
16 with self.assertRaises(AttributeError):
17 src.exceptions.does_not_exist
18
19 def test_catching_type_error_in_tests(self):
20 with self.assertRaises(TypeError):
21 src.exceptions.function_name('the_input')
22
23 def test_catching_index_error_in_tests(self):
24 a_list = [1, 2, 3, 'n']
25 with self.assertRaises(IndexError):
26 a_list[4]
27 with self.assertRaises(IndexError):
28 a_list[-5]
29
30 def test_catching_key_error_in_tests(self):
31 with self.assertRaises(KeyError):
32 {'key': 'value'}['does_not_exist']
33
34 def test_catching_zero_division_error_in_tests(self):
35 with self.assertRaises(ZeroDivisionError):
36 1 / 0
37
38 def test_catching_exceptions_in_tests(self):
39 with self.assertRaises(Exception):
40 raise Exception
41
42 def test_catching_exceptions_w_messages(self):
43 with self.assertRaisesRegex(
44 Exception, 'BOOM!'
45 ):
46 src.exceptions.raise_exception()
47
48 def test_catching_failure(self):
49 self.assertEqual(
50 src.exceptions.an_exception_handler(
51 src.exceptions.raise_exception
52 ),
53 'failed'
54 )
55
56 def test_catching_success(self):
57 self.assertEqual(
58 src.exceptions.an_exception_handler(
59 src.exceptions.does_not_raise_exception
60 ),
61 'succeeded'
62 )
63
64
65# Exceptions Encountered
66# AssertionError
67# ModuleNotFoundError
68# NameError
69# AttributeError
70# TypeError
71# IndexError
72# KeyError
73# ZeroDivisionError
solutions¶
the solutions in exceptions/src/exceptions.py from how to handle Exceptions in programs
1def function_name():
2 return None
3
4
5def raise_exception():
6 raise Exception('BOOM!')
7
8
9def does_not_raise_exception():
10 return None
11
12
13def an_exception_handler(a_function):
14 try:
15 a_function()
16 except Exception:
17 return 'failed'
18 else:
19 return 'succeeded'