-
使用 WebIDE 的文件浏览器,在你的 ~/project 目录下创建一个名为 handle_import_error.py 的新文件。
-
在编辑器中打开 handle_import_error.py,并添加以下代码:
try:
import nonexistent_module
except ImportError as e:
print(f"Error: Could not import module. {e}")
print("Please make sure the module is installed.")
else:
print("Module imported successfully.")
在这段代码中:
- 我们使用
try...except 块来尝试导入 nonexistent_module。
- 如果发生
ImportError,则执行 except 块。
- 在
except 块中,我们打印一条错误信息,表明无法导入该模块,并建议用户检查安装情况。
- 只有当
try 块成功执行(即未引发异常)时,才会执行 else 块。在这种情况下,意味着模块已成功导入。
-
保存 handle_import_error.py 文件。
-
在终端中使用以下命令运行脚本:
python handle_import_error.py
由于 nonexistent_module 并不存在,你应该会看到以下输出:
Error: Could not import module. No module named 'nonexistent_module'
Please make sure the module is installed.
这展示了如何捕获和处理 ImportError 异常。
-
现在,让我们修改脚本,以处理 requests 模块可能未安装的情况。将 handle_import_error.py 中的代码修改为以下内容:
try:
import requests
response = requests.get("https://www.example.com")
print(response.status_code)
except ImportError as e:
print(f"Error: Could not import module. {e}")
print("Please make sure the 'requests' module is installed. You can install it using 'pip install requests'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Requests module imported and request successful.")
在这段修改后的代码中:
- 我们尝试导入
requests 模块,并向 https://www.example.com 发起请求。
- 如果发生
ImportError,我们会打印一条特定的错误信息,建议用户使用 pip install requests 来安装 requests 模块。
- 我们还添加了一个通用的
except Exception as e 块,以捕获请求过程中可能出现的任何其他错误。
-
保存 handle_import_error.py 文件。
-
再次使用相同的命令运行脚本:
python handle_import_error.py
由于你在上一步中已经安装了 requests 模块,你现在应该会看到以下输出:
200
如果你没有安装 requests 模块,你将会看到 ImportError 信息。