views:

54

answers:

3

Hi there.

How should a program handle errors? Example:

A program needs the file text.txt. It must exist and be writable. What should it do if it's not writable or doesn't exist? Should it try to chown/chmod the file? Should it try to create it or just display an error message?

Or: Should it try to find a solution or just display an error message?

+6  A: 

It's up to you how to handle it. You have to define your scenarios, user interactions, and other parts of the program. Once you define those it is time to implement and test those scenarios.

Some questions to ask:

  • What data is being written to the file?
  • How critical is it that the data get saved?
  • If an error is reported, who will see the error?
  • If an error is reported, how do you expect a user to react? And what are their options?
Eilon
A: 

Your program should output an error on STDERR and return with an exit code different than zero.

For more informations :

Mat
+2  A: 

I would go with Eilon's answer for the most part but would add the following caveat - I would not try to chown/chmod a file, unless you really need to i.e. if the purpose of your program is managing file permissions or acting as an installer of some sort. This is because a) your attempted chmod/chown may not work and b) your application should respect the user privileges with which it is run - if these are not sufficient you should inform the user via whatever mechanism you do this.

Ninefingers