How do I handle signals and exceptions on macOS in C++?

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.

Handling Signals

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.

Handling Exceptions

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.

Example

#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; }

C++ macOS signals exceptions signal handling exception handling