System and device programming-exception example

// exceptions_try_except_Statement.cpp

Syntax

      __try 
{
   // guarded code
}
__except ( expression )
{
   // exception handler code
}
https://msdn.microsoft.com/en-us/library/s58ftw19.aspx

// Example of try-except and try-finally statements



#include <stdio.h>

#include <windows.h> // for EXCEPTION_ACCESS_VIOLATION

#include <excpt.h>

int filter(unsigned int code, struct _EXCEPTION_POINTERS *ep) {

   puts("in filter.");

   if (code == EXCEPTION_ACCESS_VIOLATION) {

      puts("caught AV as expected.");

      return EXCEPTION_EXECUTE_HANDLER;

   }

   else {

      puts("didn't catch AV, unexpected.");

      return EXCEPTION_CONTINUE_SEARCH;

   };

}

int main()

{

   int* p = 0x00000000;   // pointer to NULL

   puts("hello");

   __try{

      puts("in try");

      __try{

         puts("in try");

         *p = 13;    // causes an access violation exception;

      }__finally{

         puts("in finally. termination: ");

         puts(AbnormalTermination() ? "\tabnormal" : "\tnormal");

      }

   }__except(filter(GetExceptionCode(), GetExceptionInformation())){

      puts("in except");

   }

   puts("world");

}

Output:

hello
in try
in try
in filter.
caught AV as expected.
in finally. termination:
       abnormal
in except
world

when block *p=13,result is:

hello

in try1

in try2

in finally. termination:

        normal

world

(to print 16进制 using %x)


when change the order:

int main()

{

   int* p = 0x00000000;   // pointer to NULL

   puts("hello");

   __try{

      puts("in try1");

      __try{

         puts("in try2");

         *p = 13;    // causes an access violation exception;

      }__except(filter(GetExceptionCode(), GetExceptionInformation())){

      puts("in except");

   }

   }__finally{

         puts("in finally. termination: ");

         puts(AbnormalTermination() ? "\tabnormal" : "\tnormal");

      }

   puts("world");

   Sleep(2000000);

}

result is:

hello

in try1

in try2

in filter.

exception code is c0000005

caught AV as expected.

in except

in finally. termination:

        normal

world

now finally is corresponding to outer try,so of course,the outer try has no error,

the function AbnormalTermination() won't detect error

And through the code can find the exception is not user-generated(c not E),can use ReportException() to define user generated exception.

你可能感兴趣的:(expected,include,example,expression,Statements)