SEH Eceptions - generating and handling

378 views Asked by At

I want to generate and handle exceptions (SEH).
How can I write a code that will lead to an "illegal instruction"-exception?

2

There are 2 answers

1
user7860670 On

You can do something like this:

#include <Windows.h>

#include <cstdio>

::DWORD FilterFunction(::DWORD const _exception_code)
{
    if(EXCEPTION_ILLEGAL_INSTRUCTION == _exception_code)
    {
        ::std::printf("filtered\n");
        return EXCEPTION_EXECUTE_HANDLER;
    }
    else
    {
        ::std::printf("not filtered\n");
        return EXCEPTION_CONTINUE_SEARCH;
    }
}

int main()
{
    __try
    {
        ::std::printf("trying...\n");
        ::RaiseException
        (
            EXCEPTION_ILLEGAL_INSTRUCTION // exception id
        ,   0 // continuable exception
        ,   0 // args count
        ,   nullptr // args
        );             // no arguments
        ::std::printf("finished trying\n");
    }
    __except(FilterFunction(GetExceptionCode()))
    {
        ::std::printf("exception handled\n");
    }
    return 0;
}

trying...

filtered

exception handled

2
Richard Hodges On

You can raise a structured exception in Windows with:

RaiseException(EXCEPTION_ILLEGAL_INSTRUCTION, EXCEPTION_NONCONTINUABLE, 0, nullptr);

Reference:

https://msdn.microsoft.com/en-us/library/ms680552%28VS.85%29.aspx