Panic in C++
Our program demonstrates the use of exceptions for handling unexpected errors. This is the only program on the site designed to throw an exception.
#include <iostream>
#include <stdexcept>
#include <fstream>
int main() {
// We'll use exceptions throughout this site to check for
// unexpected errors. This is the only program on the
// site designed to throw an exception.
throw std::runtime_error("a problem");
// A common use of exceptions 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
// throwing an exception if we get an unexpected error when creating a new file.
std::ofstream file("/tmp/file");
if (!file) {
throw std::runtime_error("Failed to create file");
}
}
Running this program will cause it to throw an exception, print an error message, and exit with a non-zero status.
When the first exception in main
is thrown, 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 exception.
$ g++ -o panic panic.cpp
$ ./panic
terminate called after throwing an instance of 'std::runtime_error'
what(): a problem
Aborted (core dumped)
Note that in C++, exceptions are commonly used for handling many errors, unlike some languages which use error-indicating return values wherever possible.
In C++, when an exception is thrown and not caught, the program will terminate and typically provide a stack trace. The exact output may vary depending on your compiler and system settings.
It’s important to note that while exceptions in C++ serve a similar purpose to panics in some other languages, they provide more flexibility in terms of error handling and recovery. In C++, you can catch and handle exceptions at various levels of your program, allowing for more graceful error management when desired.