Using "with" context handler, and catching specific exception?
Victor Hooi
victorhooi at gmail.com
Tue Oct 22 21:11:45 EDT 2013
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 at 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
More information about the Python-list
mailing list