Is there a way to capture hardware/system exceptions, such as divide by zero?
As a general guideline, I would not recommend attempting to handle hardware exceptions: rather, let them crash the process so that you know there's a bug that you need to fix.
If you really do need to handle hardware exceptions, your solution is going to be platform-specific. On UNIX-like systems, the common interface for capturing hardware exceptions is a signal handler (usually set with sigaction()
for maximum flexibility.) If possible, signal handlers should be written in C, not in Swift. Signal handlers are extremely constrained in what they can safely do, and Swift (as with many modern languages) is not designed with signal safety in mind.
Depending on the platform you're using, there may be other interfaces that are preferred for handling hardware exceptions. For instance, hardware exceptions on Windows can be handled using Structured Exception Handling.
I believe that the better answer on Windows may be to use VEH rather than SEH. The vectored exception handling is able to chain better than SEH and are not inherently tied to the call stack.
Believe it or not, Microsoft's own documentation suggests using SEH rather than VEH. But that's not really the point—rather, the point is that hardware exception handling is platform-specific.