python 生成异常数据
时间: 2023-09-25 14:15:37 浏览: 92
生成异常数据的方法取决于你要生成的异常类型和数据类型。下面是几个例子:
1. 生成一个 `ValueError` 异常:
```python
raise ValueError("Invalid input")
```
2. 生成一个 `TypeError` 异常:
```python
raise TypeError("Expected a string but got an integer")
```
3. 生成一个 `IndexError` 异常:
```python
my_list = [1, 2, 3]
try:
print(my_list[4])
except IndexError:
print("Index out of range")
```
4. 生成一个 `KeyError` 异常:
```python
my_dict = {"a": 1, "b": 2, "c": 3}
try:
print(my_dict["d"])
except KeyError:
print("Key not found")
```
5. 生成一个 `AttributeError` 异常:
```python
class MyClass:
def __init__(self):
self.my_attribute = 42
my_instance = MyClass()
try:
print(my_instance.non_existent_attribute)
except AttributeError:
print("Attribute not found")
```
阅读全文