Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #57220

Re: Using "with" context handler, and catching specific exception?

Date 2013-10-22 03:04 +0100
From MRAB <python@mrabarnett.plus.com>
Subject Re: Using "with" context handler, and catching specific exception?
References <a2623010-97d3-4a6d-9373-e9979492b84f@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.1330.1382407479.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 22/10/2013 02:43, Victor Hooi wrote:
> Hi,
>
> I suspect I'm holding
>
> How should I use the "with" context handler as well as handling specific exceptions?
>
> For example, for a file:
>
>      with open('somefile.log', 'wb') as f:
>          f.write("hello there")
>
> How could I specifically catch IOError in the above, and handle that? Should I wrap the whole thing in a try-except block?
>
Yes, it's as simple as that.

> (For example, if I wanted to try a different location, or if I wanted to print a specific error message to the logfile).
>
>      try:
>          with open('somefile.log', 'wb' as f:
>              f.write("hello there")
>      except IOError as e:
>          logger.error("Uhoh, the file wasn't there").
>

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Using "with" context handler, and catching specific exception? Victor Hooi <victorhooi@gmail.com> - 2013-10-21 18:43 -0700
  Re: Using "with" context handler, and catching specific exception? MRAB <python@mrabarnett.plus.com> - 2013-10-22 03:04 +0100
  Re: Using "with" context handler, and catching specific exception? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-10-22 02:48 +0000
  Re: Using "with" context handler, and catching specific exception? Ben Finney <ben+python@benfinney.id.au> - 2013-10-22 14:04 +1100
    Re: Using "with" context handler, and catching specific exception? Victor Hooi <victorhooi@gmail.com> - 2013-10-21 20:27 -0700
      Re: Using "with" context handler, and catching specific exception? Ben Finney <ben+python@benfinney.id.au> - 2013-10-22 14:53 +1100
        Re: Using "with" context handler, and catching specific exception? Victor Hooi <victorhooi@gmail.com> - 2013-10-22 18:11 -0700

csiph-web