tags:

views:

125

answers:

4

The program requires the file to run, but if for any myriad number of reasons it can't be found or isn't readable, etc - what's the cleanest way to fail out of the program?

+4  A: 

If the file is required, and a missing file is abnormal, I would throw an exception. That would then be handled on a higher level, where it is possible to decide what to do about the problem. If the app absolutely can't run without the file in question, I would just terminate it gracefully with an appropriate error message to show the exact problem to its users.

And of course, I would strive to check early for this file, before allocating other resources. This way there is less unnecessary stuff done, and less unused resources to free upon abnormal termination.

Péter Török
+7  A: 

Fail as you would fail in other cases:

  • A command line program would output the unreadable file (full path) and the exact reason for not being able to read it on Stderr and exit with an error code. The functions strerror() and perror() help you in verbalizing the failure reason.
  • A Gui would post an error message like the one above and exit after acknowledgement.
Peter G.
Just a note: Always try to write the full path to the file you tried to open, not just filename.
PeterK
`strerror()` and `perror()` are both standard C and C++, so they aren't limited to Unix.
Steve M
Great, edited. I'm a Linux/Unix guy ...
Peter G.
@PeterK: when symlinking is at work, it's also worthy to print both the argument passed AND the real path :)
Matthieu M.
+1  A: 

This type of error message should always include:

  • the name by which the program tried to open the file
  • the result of strerror(errno) on Unix, or the rather more convoluted Windows equivalent.
Zack
A: 

I'm thinking of these three steps:

First: print out the name of the file with a suitable error message.

Second: clean up the resources which your program has taken. free memory, close pipes, close sockets, delete temporary files, release mutexes ... .

Third: Terminate using exit().

Green Code
On the second step, except for temporary files, afaik all of the others are taken care of by the operating system when the program exits.
ergosys
Thanks, good comment. On many platforms that is done by the operating system. But i wanted him to know what should be done.
Green Code