Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my UnhandledExceptionFilter not being called on a simple divide by zero?

I am using the following MSVC++ console application code (running on Windows 8.1, Release, Win32) to try and return a top-level exception back to me:

#include "stdafx.h"
#include <Windows.h>
#include <iostream>

using namespace std; 

LONG WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS exception)
{
    printf("Got an unhandled exception.");
    return EXCEPTION_CONTINUE_SEARCH;
}

int _tmain(int argc, _TCHAR* argv[])
{
    SetUnhandledExceptionFilter(UnhandledExceptionFilter);
    int a = 0;
    int b = 0;
    int c = a / b;
    cin.get();
    return 0;
}

My UnhandledExceptionFilter doesn't actually seem to ever get called on the divide by zero exception that is being thrown in this example, otherwise I would expect the "Got an unhandled exception" log message to show up. Why is that?

like image 893
Alexandru Avatar asked Dec 16 '22 00:12

Alexandru


2 Answers

Integer division by zero is undefined behavior. If an implementation choose to raise an exception for that (or for any other undefined behavior), that's fine. If an implementation chooses not to raise an exception for some undefined behavior, that's also fine. Whatever the implementation does when confronted with undefined behavior is fine. It's not their problem.

Apparently MSVC++ running on Windows 8.1, Win32 doesn't raise an exception on division by zero.

You should never expect undefined behavior to result in something expected.

like image 62
David Hammen Avatar answered Dec 28 '22 07:12

David Hammen


The function specified by SetUnhandledExceptionFilter() won't be called if the application is running under a debugger, the idea being that SetUnhandledExceptionFilter() should only be used to generate a crash dump and then exit an application. This isn't very useful if you have a debugger attached, so the debugger will handle the exception first.

The MSDN documentation references this:

After calling this function, if an exception occurs in a process that is not being debugged, and the exception makes it to the unhandled exception filter, that filter will call the exception filter function specified by the lpTopLevelExceptionFilter parameter.

like image 42
masrtis Avatar answered Dec 28 '22 06:12

masrtis