Dietrich
Dietrich

Reputation: 5531

Best practice for raising IOError exception in Python

I am writing a small Python interface for reading temperatures from a DS18B20 Sensor via sysfs. Besides the temperature also a status of a CRC sum can be read. To trigger a CRC error, I decided to utilize IOError:

sn = "28-000005589697"  # sensor serial number
# file containing information of temperature and if CRC is valid: 
fname = "sys/bus/w1/devices/" + sn + "/w1_slave"
with open(fname, 'f') as f: 
...
raise IOError("Invalid CRC in {}!".format(sn))

As a far I understand IOError, it has the members message, filename, errno and strerror. By my approach only message is used. It seems like I am missing something here.

What is the best practice to raise an IOError exception, so it blends in well with other errors such as disk full or file not found, etc.?

Upvotes: 4

Views: 15188

Answers (1)

knitti
knitti

Reputation: 7033

You know filename, it is the file you were reading and calculating the CRC for. For errno and strerror I would pick from the list of defined errors in libc. This is where the reasons of most IOErrors originate from, so lets keep this implementation detail for consistency. Which values to pick is somewhat arbitrary (and not completely OS independent), I'd try convey the general meaning of my problem without being too specific.

You could take one of these (the comment would be strerror):

EIO          5  /* I/O error */
EINVAL      22  /* Invalid argument */

Being too specific with such a "fake" libc error could send people debugging a problem on the wrong track.

BTW I consulted this list for existing errno's

Upvotes: 4

Related Questions