开发者

Error handling. How should a program do it?

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 writ开发者_如何学运维able 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?


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?


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.


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

For more informations :

  • http://en.wikipedia.org/wiki/Exit_status
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜