473,544 Members | 1,822 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pythonic way for handling file errors

Hello,

I would like to know what would be considered the most
Pythonic way of handling errors when dealing with files,
solutions that seem reasonable using 2.5:

-------
try:
f = open('afile', 'r')
content = f.read()
error = 200
except Exception:
error = 404
finally:
if locals().has_ke y('f'):
f.close()
------
try:
f = open('afile', 'r')
content = f.read()
except Exception:
error = 404
else:
error = 200
finally:
if locals().has_ke y('f'):
f.close()
-------
try:
f = open('afile', 'r')
content = f.read()
error = 200
except Exception:
error = 404
finally:
try:
f.close()
except Exception:
pass
-------
try:
f = None
f = open('afile', 'r')
content = f.read()
error = 200
except Exception:
error = 404
finally:
if f:
f.close()
----
try:
with open('afile', 'r') as f:
content = f.read()
error = 200
except Exception:
error = 404
----

Of the above I think I like the last one best, but I think
I'd really like to have:

with open('afile', 'r') as f with exceptions:
content = f.read()
error = 200
except Exception:
error = 404

Another words from looking at PEP343 it is the author
of the object returned by the with expression that gets
to decide if exceptions are re-raised. But it would seem
to me it should be the programmer using it that should
decide.

Of course as a newbie, I may be way off base.

Thanks,

Wink Saville

Oct 10 '07 #1
2 1844
On Oct 10, 7:41 pm, wink <w...@saville.c omwrote:
I would like to know what would be considered the most
Pythonic way of handling errors when dealing with files,
solutions that seem reasonable using 2.5:
The best way to handle errors is to catch the exceptions that are
raised by the code that handles the error. Your examples push the
problem elsewhere: you're setting an error code which has to be tested
for. But perhaps your application needs to do this for some reason
(judging from your error codes, this is some sort of web script).
...
try:
with open('afile', 'r') as f:
content = f.read()
error = 200
except Exception:
error = 404
Of all your examples, this is the best. But the catch-all exception
handler is bad: it's better to catch just file io exceptions. Also, I
think it's better to put the OK case (error 200) in an else clause to
make it clearer that it's only set when no error occurs. It's also
better to use constants in place of magic numbers.

import httplib

try:
with open('afile', 'r') as f:
content = f.read()
except IOError:
error = httplib.NOT_FOU ND
else:
error = httplib.OK

--
Paul Hankin

Oct 10 '07 #2
On Oct 10, 12:28 pm, Paul Hankin <paul.han...@gm ail.comwrote:
On Oct 10, 7:41 pm, wink <w...@saville.c omwrote:
I would like to know what would be considered the most
Pythonic way of handling errors when dealing with files,
solutions that seem reasonable using 2.5:

The best way to handle errors is to catch the exceptions that are
raised by the code that handles the error. Your examples push the
problem elsewhere: you're setting an error code which has to be tested
for. But perhaps your application needs to do this for some reason
(judging from your error codes, this is some sort of web script).
...
try:
with open('afile', 'r') as f:
content = f.read()
error = 200
except Exception:
error = 404

Of all your examples, this is the best. But the catch-all exception
handler is bad: it's better to catch just file io exceptions. Also, I
think it's better to put the OK case (error 200) in an else clause to
make it clearer that it's only set when no error occurs. It's also
better to use constants in place of magic numbers.

import httplib

try:
with open('afile', 'r') as f:
content = f.read()
except IOError:
error = httplib.NOT_FOU ND
else:
error = httplib.OK

--
Paul Hankin
Wink,

One of the problems your facing is knowing whether you managed to open
the file before reaching the finally block where you close your file.
To avoid this, I open my files right before try/finally. For me, the
only purpose in having the try/finally is to make sure my files are
properly closed, although when I'm lazy, I just let the file close it
self during garbage collection. This is what it looks like:

file = open('filename' )
try:
# read and/or process file
finally:
file.close()

Of course, this example does not handle any exceptions. In many cases,
you want these errors to propogate upward so the users of your
functions/methods can decide what needs to be done. On the other hand,
you could wrap this code with try/except/else if you wanted to handle
the exception "at the source".

Oct 10 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3188
by: Hans-Joachim Widmaier | last post by:
Hi all. Handling files is an extremely frequent task in programming, so most programming languages have an abstraction of the basic files offered by the underlying operating system. This is indeed also true for our language of choice, Python. Its file type allows some extraordinary convenient access like: for line in open("blah"):...
3
3074
by: WindAndWaves | last post by:
I am writing error handling procedures at the moment. Here are some questions: 1. Can you write a procedure that picks up any error and deals with it no matter where it happens in the database? 2. Does Access keep a list of errors in a "secret" table? 3. Is there a way to handle common errors (such as - "you need to choose from the...
21
4375
by: Anthony England | last post by:
Everyone knows that global variables get re-set in an mdb when an un-handled error is encountered, but it seems that this also happens when the variable is defined as private at form-level. So if "global variables get re-set" doesn't tell the whole story, then what does? ***please note*** I'm not looking for a solution - I'm looking for a...
4
2517
by: aaj | last post by:
Hi all I have an automated application, that runs in the middle of the night. If certain 'non system' errors occur (things like malformed files, missing files etc..), I send an automatic Email and write a record to the database. This is handled in a class. When these errors occur, once Emailed and written I want to just end the App,...
4
1919
by: Al Williams | last post by:
Hi, I have error handling in place throughout my application. I also start the application wrapped in error handling code to catch any unexpected exceptions (i.e. exceptions that occur where I haven't placed error handling code). When I run my app from the IDE, the unhandled errors are caught by the error handling code in my Sub Main...
10
2270
by: Anthony England | last post by:
(sorry for the likely repost, but it is still not showing on my news server and after that much typing, I don't want to lose it) I am considering general error handling routines and have written a sample function to look up an ID in a table. The function returns True if it can find the ID and create a recordset based on that ID, otherwise...
35
3746
by: jeffc226 | last post by:
I'm interested in an idiom for handling errors in functions without using traditional nested ifs, because I think that can be very awkward and difficult to maintain, when the number of error checks gets about 3 or so. It also gets very awkward in nested loops, where you want to check for normal loop processing in the loop condition, not...
3
1123
by: xavim | last post by:
Hi everyone, I am writing a small tool that generates a file from a list of sources. The function dictgen(dictfile, *sources) takes a list of sources path and an open file object and does the processing. I am having some problems with how to do proper error handling. One of the requirements is that the destination file should not be...
2
1867
by: Omar Abid | last post by:
Reason of this project: Error handling is one of the most difficult thing that may afford a programmer. It isn't as easy as you think and handling errors in a program some time can make errors occur! Project details: 1- New solution for handling errors in .net 2- Try...Catch...Finally Block 3- Error handling sample
0
7370
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7779
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7387
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7714
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5920
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5305
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3415
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1848
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
674
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.