> For the complete documentation index, see [llms.txt](https://lujw666.gitbook.io/learn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lujw666.gitbook.io/learn/python/00-basic/00-cuo-wu-yu-yi-chang/03-pao-chu-yi-chang.md).

# 抛出异常

## raise

使用 raise 语句抛出一个指定的异常。

```python
raise [Exception [, args [, traceback]]]
```

raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类（也就是 Exception 的子类）。

实例:

```python
# 如果 x 大于 5 就触发异常
x = 10
if x > 5:
    raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
```

如果你只想知道这是否抛出了一个异常，并不想去处理它，那么一个简单的 raise 语句就可以再次把它抛出。

```python
>>> try:
        raise NameError('HiThere')
    except NameError:
        print('An exception flew by!')
        raise
   
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: HiThere
```

## assert

assert（断言）用于判断一个表达式，在表达式条件为 false 的时候触发异常。

语法格式如下：

```python
assert expression
```

等价于：

```python
if not expression:
    raise AssertionError
```

assert 后面也可以紧跟参数:

```python
assert expression [, arguments]
```

等价于：

```python
if not expression:
    raise AssertionError(arguments)
```

实例1：

```python
>>> assert True     # 条件为 true 正常执行
>>> assert False    # 条件为 false 触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1    # 条件为 true 正常执行
>>> assert 1==2    # 条件为 false 触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

>>> assert 1==2, '1 不等于 2'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 1 不等于 2
```

实例2：

```python
import sys
assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"

# 判断当前系统是否为 Linux，如果不满足条件则直接触发异常，不必执行接下来的代码
# 接下来要执行的代码
```
