python主动抛出异常代码
时间: 2023-10-12 08:15:57 浏览: 41
以下是一个简单的 Python 代码示例,用于演示如何主动抛出异常:
```python
def divide_numbers(a, b):
if b == 0:
raise ZeroDivisionError("除数不能为零")
return a / b
try:
result = divide_numbers(10, 0)
except ZeroDivisionError as err:
print(err)
else:
print(result)
```
上面的代码定义了一个名为 `divide_numbers()` 的函数,该函数接受两个参数 `a` 和 `b`,并返回它们的商。如果除数 `b` 为零,则函数会主动抛出一个 `ZeroDivisionError` 异常,指示除数不能为零。
在主程序中,我们使用 `try-except` 语句来捕获可能抛出的异常。如果 `divide_numbers()` 函数正常返回,则代码会打印计算结果。否则,它会打印异常的错误消息,即“除数不能为零”。
相关问题
python主动抛出异常
在Python中,你可以使用`raise`关键字来主动抛出异常。你可以选择已有的异常类,如`ValueError`、`TypeError`等,或者自定义一个异常类。
以下是一些示例代码:
1. 抛出已有的异常类:
```python
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
# 测试示例
try:
result = divide(10, 0)
except ValueError as e:
print(e) # 输出:除数不能为零
```
2. 自定义异常类:
```python
class MyCustomException(Exception):
pass
def check_number(num):
if num < 0:
raise MyCustomException("数字不能为负数")
# 测试示例
try:
check_number(-5)
except MyCustomException as e:
print(e) # 输出:数字不能为负数
```
通过合理地选择异常类,可以更好地表达代码中出现的问题,并提供相关的错误信息。
python 主动抛出自定义的错误信息
在 Python 中,可以使用 `raise` 语句来抛出自定义的错误信息。具体步骤如下:
1. 定义一个异常类,继承自 `Exception` 类。
```python
class MyError(Exception):
def __init__(self, message):
self.message = message
```
2. 在需要抛出错误的地方,使用 `raise` 语句抛出这个异常。
```python
raise MyError('This is my custom error message.')
```
完整示例代码如下:
```python
class MyError(Exception):
def __init__(self, message):
self.message = message
try:
x = int(input('Enter a number: '))
if x < 0:
raise MyError('Number must be positive')
except MyError as e:
print('Error:', e.message)
else:
print('The number is:', x)
```
运行结果:
```
Enter a number: -1
Error: Number must be positive
```
注意,在 try 块中,如果发生了自定义的异常,那么 except 块中的代码将会被执行。而如果没有发生异常,则 else 块中的代码将会被执行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)