Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the cleanest way to fail gracefully when a file can't be opened in C++?

Tags:

c++

file-io

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?

like image 416
Tim Avatar asked Dec 16 '22 20:12

Tim


2 Answers

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.
like image 166
Peter G. Avatar answered May 16 '23 06:05

Peter G.


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.

like image 35
Péter Török Avatar answered May 16 '23 08:05

Péter Török