-
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
ブロック内で、モジュールをインポートできなかったことを示すエラーメッセージを出力し、ユーザーにインストールを確認するよう提案します。
else
ブロックは、try
ブロックが成功した場合(つまり、例外が発生しなかった場合)にのみ実行されます。この場合は、モジュールが正常にインポートされたことを意味します。
-
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
メッセージが表示されていたでしょう。