Solved

Exception handling???????

Posted on 1998-04-01
15
803 Views
Last Modified: 2008-02-01
will the following prevent a coredump? if not, what do i need to do?
#include <stdio.h>

void main(void)
{
  char *abc = NULL;

  try {
    *abc = 'h';
  }

  catch(...) {
    puts("NO!!!");
  }
}
0
Comment
Question by:happyloman
  • 4
  • 3
  • 3
  • +3
15 Comments
 
LVL 15

Expert Comment

by:Tommy Hui
ID: 1183990
No, it does not. You will need to change your code to

  void main()
  {
    char* abc = NULL;

    if (abc)
      *abc = 'h';
  }
 
 
0
 

Author Comment

by:happyloman
ID: 1183991
I want to intentionally create a core dump.  I am trying to see if there is a way for the exception handler to catch all coredumps and to NOT create the core file
0
 
LVL 22

Expert Comment

by:nietod
ID: 1183992
answer coming.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1183993
Exceptions occcur when the source detects an error and throws the exception.  That is, exceptions occur manually not automatically.  (One exception to this rule is the bad cast exception.)  But in general you must throw an exception or call a procedure that throws an exception (some of thelibrary procedures throw exceptions.)  So there is no exception generated by using an invalid pointer.  You would need to have code, like thui suggested, that detects the NULL pointer and throws an exception rather than using the pointer.

Thus you cannot use exceptions to prevent the core dumps because the core dumps are occuring when serios errors occur AND exceptions are not thrown.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1183994
Coredumps are not the domain of C++.  They are under the control of the debugger or operating system.  Try looking for options in the debugger/OS for preventing core dumps.
0
 
LVL 23

Expert Comment

by:chensu
ID: 1183995
I disagree with thui and nietod. You'd better reject it and accept mine. :-)

If you want to catch it, you can use Structured Exception Handling (the try-except statement). Here is an example:

// Example of try-except and try-finally statements
#include "stdio.h"

void 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");
        }
    }__except(puts("in filter"), 1){
        puts("in except");
    }
    puts("world");
}

The documentation is under
Platform SDK\Windows Base Services\Debugging and Error Handling\Structured Exception Handling
0
 
LVL 23

Expert Comment

by:chensu
ID: 1183996
Sorry to forget one thing. That is a Microsoft extension to the C and C++ languages. It is platform-dependent.

I thought I was on the Windows Programming Topic Area.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 11

Expert Comment

by:alexo
ID: 1183997
Win32 implements what's called "structured exception handling".  The OS itself generates and handles exceptions.  In C, you can use MS proprietary extentions (__try, __catch and __finally).  In C++ there is a mechanism that translates OS exceptions to C++ exceptions.  This however is not portable to other platforms.
0
 
LVL 11

Expert Comment

by:alexo
ID: 1183998
Oops, it's __except, not __catch.

Translation can be implemented thus:

////////////////////////////////////////////////////////////////////////////////

#include <iostream.h>
#include <process.h>

#pragma warning(disable: 4201 4514)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <eh.h>


struct SE
{
      SE(unsigned int n, EXCEPTION_POINTERS* p): code(n), pointers(p) {}
      unsigned int code;
      EXCEPTION_POINTERS* pointers;
};


void SehXlate(unsigned int n, EXCEPTION_POINTERS* p)
{
      throw SE(n, p);
}


int main()
{
      _set_se_translator(SehXlate);

      try
      {
            int* p = 0;
            *p = 5;
      }

      catch (SE& se)
      {
            cout << "caught OS exception " << hex << se.code << endl;
      }

      return 0;
}

////////////////////////////////////////////////////////////////////////////////

0
 

Author Comment

by:happyloman
ID: 1183999
Thank you for your great responses.

I am at fault for not being more specific, however.

Chensu and Alexo, I tried both of your solutions but was unsucessful.
--Chensu>>

"chen.C: In function `int main(...)':
chen.C:13: (Each undeclared identifier is reported only once
chen.C:13: for each function it appears in.)
chen.C:13: parse error before `{'
chen.C: At top level:
chen.C:16: warning: implicit declaration of function `int Puts(...)'
chen.C:16: warning: ANSI C++ forbids declaration `__except' with no type or stor
age class
chen.C:16: warning: initializer list being treated as compound expression
chen.C:16: syntax error before `{'
chen.C:19: warning: ANSI C++ forbids declaration `puts' with no type or storage
class
chen.C:19: `int puts' redeclared as different kind of symbol
/usr/tools/lib/gcc-lib/i386-unknown-solaris2.6/2.7.2.2/include/stdio.h:282: prev
ious declaration of `int puts(const char *)'
chen.C:19: warning: initialization to `int' from `char *' lacks a cast
chen.C:20: parse error before `}'

--Alexo>>
alexo.C:2: process.h: No such file or directory
alexo.C:6: windows.h: No such file or directory
alexo.C:7: eh.h: No such file or directory

/******************************PLEASE NOTE ********************************/
I should let you know that I am on X-86 machines with Solaris-2.6-i86pc, SunOS5.6.
/******************************PLEASE NOTE*********************************/

Here is a different statement of my question again, then.

/*********  restatement of original question *********/

I am using an api function called "sometimes_dumps()" in a loop. I would like
to have my main function NOT coredump when this happens, but to handle
the exception and proceed to the next iteration of the while loop

void sometimes_dumps(int abc)

#include <stdio.h>


void call_the_api(int abc)
{
  /*
   * do some stuff
   */
  sometimes_dumps(abc) /* call the api, which sometimes crashes */
  /*
   * do some other stuff
   */
}

void main (void)
{
  int ten_numbers[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  int index = 0;


  while(1)
  {
    call_the_api(ten_numbers[index])
    index++;
  }
}

/******* end of program ******/


So, if the sometimes_dumps crashes on, say, ten_numbers[5], I would like the
program to handle it, and proceed to ten_numbers[6].

 Is this possible, or is Nietod correct?

THANKS!!!!!



0
 

Author Comment

by:happyloman
ID: 1184000
I am using g++ compiler
0
 

Author Comment

by:happyloman
ID: 1184001
oops,

change the while loop condition to "while (index < 10)"
0
 
LVL 1

Accepted Solution

by:
rcabanie earned 600 total points
ID: 1184002
I assume you are working with a unix system.
Since you didn't specify what system, I will give you the most general solution.
When a memory error occurs on a unix system, a sigbus, sigsegv or a similar signal is sent to the process. By default this will call the default signal handler and this default handler will generate a core file and terminate the process.

You can override this default signalhandler, so it will throw an exception. The mechanism to override it is standard, but not all unix versions support it. (But they all will have a similar way to implement it).

This is how your code could look like:

void DefaultHandler(int) // or void DefaultHandler() -> depends on unix version
{
    throw myclass; // throw custom class here
}

void installsignalhandlers()
{
      struct sigaction act;

      // new way
      act.sa_flags = SA_SIGINFO;
      act.sa_handler = NULL;
      act.sa_sigaction = DefaultHandler;
      sigfillset(&act.sa_mask);

      sigaction(SIGTRAP, &act, NULL);
      sigaction(SIGBUS, &act, NULL);
      sigaction(SIGILL, &act, NULL);
      sigaction(SIGFPE, &act, NULL);
      sigaction(SIGSEGV, &act, NULL);
}

call installsignalhandlers in every thread where you want to have this behaviour.
I can not garantuee that this will always work. If the program crashes because of a stack problem or an out of memory  situation, the signal handler itself will crash (and this will trigger a coredump).

0
 
LVL 23

Expert Comment

by:chensu
ID: 1184003
My solution uses the Microsoft extension. g++ compiler does not accept it.
0
 
LVL 1

Expert Comment

by:rcabanie
ID: 1184004
I am not using a compiler extension.
This is a feature of the unix operating system.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now