Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #57219 > unrolled thread
| Started by | Victor Hooi <victorhooi@gmail.com> |
|---|---|
| First post | 2013-10-21 18:43 -0700 |
| Last post | 2013-10-22 18:11 -0700 |
| Articles | 7 — 4 participants |
Back to article view | Back to comp.lang.python
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
| From | Victor Hooi <victorhooi@gmail.com> |
|---|---|
| Date | 2013-10-21 18:43 -0700 |
| Subject | Using "with" context handler, and catching specific exception? |
| Message-ID | <a2623010-97d3-4a6d-9373-e9979492b84f@googlegroups.com> |
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?
(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").
Cheers,
Victor
[toc] | [next] | [standalone]
| From | MRAB <python@mrabarnett.plus.com> |
|---|---|
| Date | 2013-10-22 03:04 +0100 |
| Message-ID | <mailman.1330.1382407479.18130.python-list@python.org> |
| In reply to | #57219 |
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").
>
[toc] | [prev] | [next] | [standalone]
| From | Steven D'Aprano <steve+comp.lang.python@pearwood.info> |
|---|---|
| Date | 2013-10-22 02:48 +0000 |
| Message-ID | <5265e770$0$29981$c3e8da3$5496439d@news.astraweb.com> |
| In reply to | #57219 |
On Mon, 21 Oct 2013 18:43:39 -0700, Victor Hooi wrote:
> try:
> with open('somefile.log', 'wb' as f:
> f.write("hello there")
> except IOError as e:
> logger.error("Uhoh, the file wasn't there").
I hope that this isn't what you are actually doing. IOError is not just
for "File Not Found".
py> open("/home")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 21] Is a directory: '/home'
py> open("/root/foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 13] Permission denied: '/root/foo'
--
Steven
[toc] | [prev] | [next] | [standalone]
| From | Ben Finney <ben+python@benfinney.id.au> |
|---|---|
| Date | 2013-10-22 14:04 +1100 |
| Message-ID | <mailman.1331.1382411066.18130.python-list@python.org> |
| In reply to | #57219 |
Victor Hooi <victorhooi@gmail.com> writes:
> try:
> with open('somefile.log', 'wb' as f:
> f.write("hello there")
> except IOError as e:
> logger.error("Uhoh, the file wasn't there").
IOError, as Steven D'Aprano points out, is not equivalent to “file not
found”. Also, you're not doing anything with the exception object, so
there's no point binding it to the name ‘e’.
What you want is the specific FileNotFoundError:
try:
with open('somefile.log', 'wb' as f:
f.write("hello there")
except FileNotFoundError:
logger.error("Uhoh, the file wasn't there").
See <URL:http://docs.python.org/3/library/exceptions.html#FileNotFoundError>.
--
\ “Choose mnemonic identifiers. If you can't remember what |
`\ mnemonic means, you've got a problem.” —Larry Wall |
_o__) |
Ben Finney
[toc] | [prev] | [next] | [standalone]
| From | Victor Hooi <victorhooi@gmail.com> |
|---|---|
| Date | 2013-10-21 20:27 -0700 |
| Message-ID | <829a6777-3410-49ea-8652-ea1e4ceb9cd2@googlegroups.com> |
| In reply to | #57224 |
Hi,
Thanks for the replies =).
Aha, good point about IOError encapsulating other things, I'll use FileNotFoundError, and also add in some other except blocks for the other ones.
And yes, I didn't use the exception object in my sample - I just sort. I'd probably be doing something like this.
logger.error("Some error message - %s" % e)
So is the consensus then that I should wrap the "with" in a try-except block?
try:
with open('somefile.log', 'wb') as f:
f.write("hello there")
except FileNotFoundError as e:
logger.error("Uhoh, the file wasn't there - %s" % e)
Cheers,
Victor
On Tuesday, 22 October 2013 14:04:14 UTC+11, Ben Finney wrote:
> Victor Hooi <victorhooi@gmail.com> writes:
>
>
>
> > try:
>
> > with open('somefile.log', 'wb' as f:
>
> > f.write("hello there")
>
> > except IOError as e:
>
> > logger.error("Uhoh, the file wasn't there").
>
>
>
> IOError, as Steven D'Aprano points out, is not equivalent to “file not
>
> found”. Also, you're not doing anything with the exception object, so
>
> there's no point binding it to the name ‘e’.
>
>
>
> What you want is the specific FileNotFoundError:
>
>
>
> try:
>
> with open('somefile.log', 'wb' as f:
>
> f.write("hello there")
>
> except FileNotFoundError:
>
> logger.error("Uhoh, the file wasn't there").
>
>
>
> See <URL:http://docs.python.org/3/library/exceptions.html#FileNotFoundError>.
>
>
>
> --
>
> \ “Choose mnemonic identifiers. If you can't remember what |
>
> `\ mnemonic means, you've got a problem.” —Larry Wall |
>
> _o__) |
>
> Ben Finney
[toc] | [prev] | [next] | [standalone]
| From | Ben Finney <ben+python@benfinney.id.au> |
|---|---|
| Date | 2013-10-22 14:53 +1100 |
| Message-ID | <mailman.1334.1382414051.18130.python-list@python.org> |
| In reply to | #57227 |
Victor Hooi <victorhooi@gmail.com> writes:
> Aha, good point about IOError encapsulating other things, I'll use
> FileNotFoundError, and also add in some other except blocks for the
> other ones.
Or not; you can catch OSError, which is the parent of FileNotFoundError
<URL:http://docs.python.org/3/library/exceptions.html#exception-hierarchy>,
but don't assume in your code that it means anything more specific.
You should only catch specific exceptions if you're going to do
something specific with them. If all you want to do is log them and move
on, then catch a more general class and ask the exception object to
describe itself (by using it in a string context).
In versions of Python before 3.3, you have to catch EnvironmentError
<URL:http://docs.python.org/3.2/library/exceptions.html#EnvironmentError>
and then distinguish the specific errors by their ‘errno’ attribute
<URL:http://docs.python.org/3.2/library/errno.html>::
import errno
try:
with open('somefile.log', 'wb') as f:
f.write("hello there")
except EnvironmentError as exc:
if exc.errno == errno.ENOENT:
handle_file_not_found_error()
elif exc.errno == errno.EACCES:
handle_permission_denied()
elif exc.errno == errno.EEXIST:
handle_file_exists()
…
else:
handle_all_other_environment_errors()
That's much more clumsy, which is why it was improved in the latest
Python. If you can, code for Python 3.3 or higher.
--
\ “Unix is an operating system, OS/2 is half an operating system, |
`\ Windows is a shell, and DOS is a boot partition virus.” —Peter |
_o__) H. Coffin |
Ben Finney
[toc] | [prev] | [next] | [standalone]
| From | Victor Hooi <victorhooi@gmail.com> |
|---|---|
| Date | 2013-10-22 18:11 -0700 |
| Message-ID | <0b3bcf40-2432-45c4-863a-ccbecb394579@googlegroups.com> |
| In reply to | #57231 |
Hi,
I'm actually on Python 2.7, so we don't have access to any of those nice new exceptions in Python 3.3 =(:
http://docs.python.org/2.7/library/exceptions.html#exception-hierarchy
@Ben - Good point about just catching the more general exception, and just printing out the string message.
I suppose in most cases, we won't be doing anything special for the different types (e.g. file not found, permission error, is a directory etc.) - it'll just be going into logs.
Is there anything wrong with me just catching "Exception" in this case of opening a file, and printing the message from there?
Cheers,
Victor
On Tuesday, 22 October 2013 14:53:58 UTC+11, Ben Finney wrote:
> Victor Hooi <victorhooi@gmail.com> writes:
>
>
>
> > Aha, good point about IOError encapsulating other things, I'll use
>
> > FileNotFoundError, and also add in some other except blocks for the
>
> > other ones.
>
>
>
> Or not; you can catch OSError, which is the parent of FileNotFoundError
>
> <URL:http://docs.python.org/3/library/exceptions.html#exception-hierarchy>,
>
> but don't assume in your code that it means anything more specific.
>
>
>
> You should only catch specific exceptions if you're going to do
>
> something specific with them. If all you want to do is log them and move
>
> on, then catch a more general class and ask the exception object to
>
> describe itself (by using it in a string context).
>
>
>
>
>
> In versions of Python before 3.3, you have to catch EnvironmentError
>
> <URL:http://docs.python.org/3.2/library/exceptions.html#EnvironmentError>
>
> and then distinguish the specific errors by their ‘errno’ attribute
>
> <URL:http://docs.python.org/3.2/library/errno.html>::
>
>
>
> import errno
>
>
>
> try:
>
> with open('somefile.log', 'wb') as f:
>
> f.write("hello there")
>
> except EnvironmentError as exc:
>
> if exc.errno == errno.ENOENT:
>
> handle_file_not_found_error()
>
> elif exc.errno == errno.EACCES:
>
> handle_permission_denied()
>
> elif exc.errno == errno.EEXIST:
>
> handle_file_exists()
>
> …
>
> else:
>
> handle_all_other_environment_errors()
>
>
>
> That's much more clumsy, which is why it was improved in the latest
>
> Python. If you can, code for Python 3.3 or higher.
>
>
>
> --
>
> \ “Unix is an operating system, OS/2 is half an operating system, |
>
> `\ Windows is a shell, and DOS is a boot partition virus.” —Peter |
>
> _o__) H. Coffin |
>
> Ben Finney
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web