编写一个程序,从文件中读取若干行数据,若发生错误则抛出自定义的异常,否则将它们存储到另一个文件中
时间: 2024-03-02 12:53:29 浏览: 14
好的,以下是代码示例:
```python
# 自定义异常类
class ReadFileError(Exception):
pass
# 定义函数,从文件中读取若干行数据并将其存储到另一个文件中
def read_and_write(file1, file2):
try:
with open(file1, "r") as f1:
lines = f1.readlines()
except Exception as e:
# 如果读取文件时发生错误,则抛出自定义异常
raise ReadFileError("读取文件时发生错误!") from e
else:
with open(file2, "w") as f2:
# 将读取的行写入到另一个文件中
for line in lines:
f2.write(line)
# 调用函数,并进行异常处理
try:
read_and_write("input.txt", "output.txt")
except ReadFileError as e:
print("自定义异常:", e)
except Exception as e:
print("其他异常:", e)
```
以上代码中,我们首先定义了一个名为`ReadFileError`的自定义异常类。接着,我们定义了一个名为`read_and_write`的函数,该函数接受两个文件名参数`file1`和`file2`,并尝试从`file1`文件中读取多行数据,如果读取成功则将这些数据写入`file2`文件中。如果读取`file1`文件时发生错误,则抛出自定义异常`ReadFileError`。在`try`代码块中,我们调用`read_and_write`函数,并使用`except`代码块捕获了自定义异常和其他异常,并分别打印异常信息。