jestro
jestro

Reputation: 2593

Best cross platform practices for dealing with a fatal error in C?

Outside of logging the failure to stderr and a log file, how should I deal with a fatal error?

example:

VkResult result = vkCreateInstance(&createInfo, NULL, &vulkanInfo->instance);
if (result != VK_SUCCESS) {
    // ???
}

If vkCreateInstance fails, it's all over. The app cannot continue. What should I do?

Targets are Windows, Mac, Linux, Switch, and more.

I realize this is a very open ended question. I’m just curious how the great minds here deal with it.

Upvotes: 0

Views: 131

Answers (2)

Brendan
Brendan

Reputation: 37232

Best cross platform practices for dealing with a fatal error in C?

Your code is dealing with Vulkan, so it's reasonable to assume that almost everyone using your software will be using a GUI and will not look at (and never see) anything sent to stdout or stderr. Instead; they will expect a "GUI specific notification" (a dialog box).

There's multiple different "cross platform GUI toolkit" libraries online to choose from (if you don't feel like writing a minimal wrapper for a dialog box and nothing else).

Upvotes: 2

KamilCuk
KamilCuk

Reputation: 140990

how should I deal with a fatal error?

The app cannot continue

Because The app cannot continue you should stop your application. A properly written application would:

  • print an error message to stderr
  • stop and join and synchronize all threads
  • free all dynamically allocated memory
  • close all open files
  • generally clean up all shared resources if needed (I think of shared memory)
  • exit the application with an error

To be (almost extremely unnecessarily) portable, you can use exit(EXIT_FAILURE) to notify the system that your application exited with an error (but better use exit(EXIT_FAILURE) for readability). For the platforms you target, use exit() with any other value than 0 - exit(0) means application succeeded. For many applications, some specific exit values are also used to notify the upper application of what specific error happened, like grep exits 0 if it filtered some lines, 1 if no lines were filtered, and other exit codes if an error occurred (like for example the file does not exist).

Upvotes: 3

Related Questions