correct way to catch exception with Python 'with' statement
Thomas 'PointedEars' Lahn
PointedEars at web.de
Mon Nov 28 07:30:34 EST 2016
Ganesh Pal wrote:
> I am using Python 2.7 and Linux
As a rule of thumb¹, use at least Python 3.3 for new programs.
> What will be the best way to catch the exception in the above program ?
> Can we replace both the with statement in the above program with
> something like below
>
> try:
> for i in range(1000):
> with open(os.path.join(QA_TEST_DIR,"filename%d" %i),'w') as
> f:
> f.write("hello")
> except IOError as e:
> raise
If you do it like this, you will have a hard time figuring out what caused
the exception, and it becomes the harder the more you do in the loop.
Because *several* statements could throw an exception of the *same* type.
Therefore, as a rule of thumb¹, if you catch exceptions, catch them closest
to where they could occur:
for i in range(1000):
try:
with open(os.path.join(QA_TEST_DIR, "filename%d" % i), 'w') as f:
try:
f.write("hello")
except … as e:
raise e
except … as e:
raise e
This is just an example; you do not have to just re-raise the exception;
“raise” is just where your custom exception handling, if any, should be.
For example, if f.write() fails with an IOError, you could decide to ignore
that and “continue” with the next file, whereas you may decide that failing
to open a file is so grave a problem that you want to abort the program at
this point.
Finally, use uniform indentation and spacing in your code; the former is
even more important in Python than in other programming languages because
indentation makes a block statement in Python. Use a Python-aware editor to
make it easy to create uniform indentation by use of the Tab key, and a
reformatting feature for existing code. I can recommend Atom [0] with the
packages “autocomplete-python”, “linter-pylint”, “python-isort”, and
“python-tools” (“language-python” is a built-in); and Vim [1] with
if has("syntax")
…
syntax on
…
endif
…
filetype plugin indent on
in ~/.vimrc and a ~/.vim/after/ftplugin/python.vim containing
setlocal expandtab
setlocal shiftwidth=4
setlocal softtabstop=4
_______
¹ YMMV
[0] <https://atom.io/>
[1] <http://www.vim.org/>
--
PointedEars
Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
More information about the Python-list
mailing list