Converting floating point exceptions into C++ exceptions

前端 未结 5 886
栀梦
栀梦 2021-02-06 08:41

Is it possible to convert floating point exceptions (signals) into C++ exceptions on x86 Linux?

This is for debugging purposes, so nonportability and imperfection is oka

相关标签:
5条回答
  • 2021-02-06 09:19

    The basic idea will be for you to install the appropriate signal handlers for floating point exceptions. Inside your signal handler, you can throw an exception (or send a user-defined signal to another process which will raise the exception, or send a message to another thread for something similar, etc. etc. etc). There are any number of ways to actually throw the exception - the main thing is to handle the signal.

    0 讨论(0)
  • 2021-02-06 09:20

    Due to the way signals and exceptions work, you can't do it immediately when the signal is thrown - exceptions rely on certain aspects of the stack that aren't true when a signal handler gets called.

    You can set a global variable in the signal handler, and then check this at key points in the program and throw an exception if it's set. This doesn't give you the exact information about the thrown exception, though.

    0 讨论(0)
  • 2021-02-06 09:24

    the gcc option -fnon-call-exceptions might be of some use to you. Couldn't find any documentation on it though so your mileage may vary.

    0 讨论(0)
  • 2021-02-06 09:35

    If your C++ standard library implementation supports the TR1 functions fetestexcept, feraiseexcept and feclearexcept (mine doesn't yet so I can't test this) you can detect five kinds of floating point errors and then you can throw whatever exceptions you want.

    See here for a description of these functions.

    I also recommend section 12.3, "Managing the Floating Point Environment," of the book The C++ Standard Library Extensions: A Tutorial and Reference by Pete Becker, ISBN-13: 9780321412997, for an excellent description of these functions with sample code.

    alt text

    0 讨论(0)
  • 2021-02-06 09:40

    I don't have a ready made solution, but one thing you could look at are signals (not sure whether you can safely throw C++ exceptions from them, but it should help for debugging anyway.)

    You could install a signal handler for SIGFPE, and use that for your debugging purposes.

    0 讨论(0)
提交回复
热议问题