Python – エラー(withと例外処理)

Python

Python の トラブルに関する覚書

try と with

次のコードを実行すると、Google Colaboratory では 正常に動作するのに Microsoft Visual Studio 2019 では動作はするけど エラーの Traceback も一緒に吐き出す。

ちなみに 「test.txt」は存在しません。

try:
    with open("test.txt", mode = "r") as f:
        s = f.read()
 
    print(s)
except Exception as e:
    print(str(type(e)))

Google Colaboratory の実行結果

<class 'FileNotFoundError'>

Microsoft Visual Studio 2019 の実行結果

<class 'FileNotFoundError'>
Traceback (most recent call last):
  File "C:\・・・\Python37_64\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\・・・\Python37_64\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  < 省略 >
IndexError: list index out of range

しかも キャッチしているエラーと全く関係無い? Traceback 吐き出している(涙

CUIで 実行すると 正常なので IDEの問題だと思われます。

また、色々 試すと with で open するのがダメみたいだ。
次のコードなら エラーを出さないです。

try:
    f = open("test.txt", mode = "r")
    s = f.read()
    f.close
 
    print(s)
except Exception as e:
    print(str(type(e)))
<class 'FileNotFoundError'>

そして、withと同等にするなら こうかな

try:
    f = open("test.txt", mode = "r")
    try:
        s = f.read()
    finally:
        f.close
        
    print(s)
except Exception as e:
    print(str(type(e)))
<class 'FileNotFoundError'>

ふむ。 困ったものだ。

コメント

タイトルとURLをコピーしました