In macOS, handling signals and exceptions in C++ can be vital for ensuring that your application behaves correctly during runtime errors or interrupts. This usually involves using signal handling functions provided by the C standard library and leveraging C++ exception handling features.
To handle signals in C++, you can use the signal() function, which allows you to specify a handler for various signals, like SIGINT, SIGTERM, etc.
C++ provides a robust exception handling mechanism using try, catch, and throw keywords. You can catch standard exceptions or create custom exceptions for your application.
#include
#include
#include
void signalHandler(int signum) {
std::cout << "Interrupt signal (" << signum << ") received.\n";
// Clean up and close up stuff here
exit(signum);
}
class CustomException : public std::exception {
public:
const char* what() const noexcept override {
return "Custom Exception Occurred";
}
};
int main() {
// Register signal handler
signal(SIGINT, signalHandler);
try {
// Simulating some code execution
std::cout << "Program is running. Press Ctrl+C to trigger the signal." << std::endl;
throw CustomException(); // throw an exception
} catch (const CustomException& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?