1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| #include <iostream>
#include <limits>
#include <csignal>
#include <cfenv>
#include <stdexcept>
// Global function to handle SIGFPE and throw an exception
void signal_handler(int signal) {
if (signal == SIGFPE) {
throw std::runtime_error("Floating-point exception: signaling NaN encountered!");
}
}
int main() {
// Register SIGFPE handler to throw an exception
// It must have a signal handler, otherwise, this program would just silently crash
try {
// Register SIGFPE handler to throw an exception
std::signal(SIGFPE, signal_handler);
// Enable floating-point exceptions for invalid operations
feenableexcept(FE_INVALID);
// Create a signaling NaN
double snan = std::numeric_limits<double>::signaling_NaN();
std::cout << "Attempting to use signaling NaN..." << std::endl;
// Perform an operation that will trigger SIGFPE
double result = snan + 1.0;
std::cout << "This won't execute: " << result << std::endl;
} catch (const std::exception &e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
|