# 8. 断言异常




### 背景

我们有时候需要断言一些方法会抛出异常，这些异常需要符合我们的预期。

### 代码

新建```test_exception.py```文件，内容如下

```python
import unittest

class DivZeroTestCase(unittest.TestCase):

    def test_should_raise_exception(self):
        with self.assertRaises(ZeroDivisionError):
            1 / 0

if __name__ == '__main__':
    unittest.main()

```

### 运行及结果

```
$ python test_exception.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

```

### 我们能学到什么

* 上面的例子断言了当0作为除数的时候会抛出```ZeroDivisionError```
* 断言异常是有套路的，使用```with```语句加```assertRaises```，assertRaises的参数中传入预期的异常(这些异常可能需要先import进来)，在with的子句中放上会抛出异常的语句或表达式




原始封面

![课程图片](https://images.unsplash.com/photo-1573496130407-57329f01f769?w=300)


