pythonにおけるwith異常処理とJAVAにおける類似の比較

1001 ワード

一般的にはpythonの異常処理はtry...except...finallyで処理されます。例えば、ファイルを開けます。
f = open(filename)
try:
    ''' do something '''
except IOError:
    print('I/O error')
finally:
    f.close()
このようにする欠点は非常に面倒です。特に中に入れ子のtry…exceptの文があれば、ノギスを入れるのを待ってください。だからpythonはwithキーワードを提供してこの問題を解決します。以上のコードは以下のようになります。
with open(filename) as f:
    ''' do something'''
一言になりましたが、簡単になりましたか?複数の処理も可能です。
with open(file1) as f1, open(file2) as f2:
   ''' do something'''
でもwithを使って直接にエラーを投げます。今はwithの中で特別にエラーを処理する方法がありません。
同様に、JAVA 7以降のバージョンも同様のものを提供しています。
InputStream i = getStream()
try {
  // do something
} catch(Exception e) {
  e.printStack();
} finally {
  try {
    i.close();
  } catch(Exception e) {
    e.printStack();
  }
}
になります
try(IntpuStream i = getStream()) {
  // do something
} catch(Exception e) {
  e.printStack();
}