Panic in C
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
void panic(const char* message) {
fprintf(stderr, "panic: %s\n", message);
exit(1);
}
int main() {
// We'll use panic throughout this site to check for
// unexpected errors. This is the only program on the
// site designed to panic.
panic("a problem");
// A common use of panic is to abort if a function
// returns an error value that we don't know how to
// (or want to) handle. Here's an example of
// panicking if we get an unexpected error when creating a new file.
FILE* file = fopen("/tmp/file", "w");
if (file == NULL) {
panic(strerror(errno));
}
return 0;
}
In C, we don’t have a built-in panic
function like in some other languages. Instead, we’ve created a simple panic
function that prints an error message to stderr and exits the program.
Running this program will cause it to panic, print an error message, and exit with a non-zero status.
$ gcc panic.c -o panic
$ ./panic
panic: a problem
When the first panic
in main
is called, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first panic
call.
Note that unlike some languages which use exceptions for handling of many errors, in C it is idiomatic to use error codes and check return values wherever possible. The panic
function here is used to simulate the behavior of Go’s panic
, but it’s not a standard practice in C programming.
In C, error handling typically involves checking return values from functions and using the global errno
variable along with functions like perror
or strerror
to get more information about errors.