with exceptions?

Marko Rauhamaa marko at pacujo.net
Wed Dec 19 06:44:32 EST 2018


ram at zedat.fu-berlin.de (Stefan Ram):

> try:
>     with open( 'file', 'r' ) as f:
>         use( f )
> except Exception as inst:
>     print( inst )
>
>   Is target code the correct way to use »with« with together
>   with »except«?
>
>   Or is it recommended to continue to use »finally« in such
>   cases?

I'd advice against such ambiguous use of exceptions. I'd write:

  try:
      f = open('file')
  except WhatEverException as e:
      print(e)
  else:
      with f:
          try:
              use(f)
          except OtherException as e:
              print(e)


Marko


More information about the Python-list mailing list