-3

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

j12
  • 45
  • 5

2 Answers2

1

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

user7860670
  • 35,849
  • 4
  • 58
  • 84
  • Thanks for your reply Yes, it's clear that Raise Exception can be used . But in the task it is necessary to describe the code that will lead to the EXCEPTION_ILLEGAL_INSTRUCTION – j12 Oct 09 '18 at 14:45
0

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

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • Thanks for your reply Yes, it's clear that Raise Exception can be used . But in the task it is necessary to describe the code that will lead to the EXCEPTION_ILLEGAL_INSTRUCTION – j12 Oct 09 '18 at 14:45
  • @j12 interesting assignment. There is no intrinsic for this AFAIA, so 2 options: 1 - inline assembly, 2 - Compile with cpu extensions you know the host computer does not have (e.g. SSE2 etc) – Richard Hodges Oct 09 '18 at 14:51