Главная страница | назад





Article #16750: Catching an access violation exception

 Question and Answer Database

FAQ1750C.txt   Catching an access violation exception
Category   :C/C++ Language Issues
Platform    :All
Product    :BC++  5.x

Question:

Why does my attempt at catching an access violation fail?

main()
{
  char *ptr;
  ptr=NULL;
  try
  {
    *ptr=5;
  }
  catch(...)
  {
    cerr << "Caught exception" << endl;
  }
}

Answer:

You are trying to catch a C++ exception ( which means that there
must be a matching "throw" somewhere for you to catch anything ).
You could use that construct to handle thrown objects ( like 
xalloc for failures in calls to new ).
For OS excpetions like access violations, you should be using 
OS structured exception handling:


// catch.cpp

#include 
#include 

main()
{
  char *ptr;

  // point the pointer to an
  // invalid address
  ptr=NULL;

  try
  {
    // attempt to assign a value
    // to the location pointed
    // to by the pointer
    *ptr=5;
  }
  except(EXCEPTION_EXECUTE_HANDLER)
  {
    // report the exception type
    cerr << "Caught exception code: 0x"
      << hex << GetExceptionCode()
      << endl;
  }
}

see:
__try
__except
RaiseException

7/2/98 10:32:32 AM
 

Last Modified: 01-SEP-99