LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   try catch(...) (https://www.linuxquestions.org/questions/linux-newbie-8/try-catch-196356/)

Sinner6 06-22-2004 09:11 AM

try catch(...)
 
I am a windows programmer who is porting an app to linux. It is going well so far but I am hitting a seg-fault. My error handing code seems to be at issue.

Code

try {
ReallyUglyFunction(); //throw lots of std::exceptions plus many others including divide by zero or referencing bad memory
}
catch (exception e) {
// catches what I expect
}
catch (...) {
// never catches anything in linux
}


In Windows catch(...) is a fail safe that catches everything.
In Linux catch(...) doesn't seem to catch anything.

What do I need to do to fix this?

Thanks

mascdman 06-22-2004 10:26 PM

From what I've seen, errors like division by zero and segmentation violations result in signals being forced on a process by the kernel. You can install signal handlers in your C++ program like so:
Code:

#include <exception>
#include <iostream>
#include <signal.h>

using namespace std;

void sighandler(int);

void sighandler(int signum)
{
  switch(signum)
    {
    case 8:  cout << "Caught SIGFPE\n"; exit(1);
    case 11: cout << "Caught SIGSEGV\n"; exit(2);
    default: cout << "I shouldn't be here!\n";
    }
}

int main(void)
{
  int a = 1, b = 0;
  int* d = 0;

  if (signal(SIGFPE, &sighandler) == SIG_ERR)
      cout << "Couldn't install FPE signal handler!\nExpect a core dump\n";
  if (signal(SIGSEGV, &sighandler) == SIG_ERR)
      cout << "Couldn't install SEGV signal handler!\nExpect a core dump\n";

#ifndef SKIP
  cout << "Div by zero\n";
  int c = a/b;
#else
  cout << "Playing with bad memory\n";
  d[0] = 0;
#endif
}

Once you've run and compiled, you should get
Code:

[mascdman@odin tmp][ :) ]$ ./a.out
Div by zero
Caught SIGFPE
[mascdman@odin tmp][ :( 1 ]$

or
Code:

[mascdman@odin tmp][ :) ]$ ./a.out
Playing with bad memory
Caught SIGSEGV
[mascdman@odin tmp][ :( 2 ]$

To get a list of other signals, run man -S 7 signal. Hope this helps.

--mascdman

Tinkster 06-24-2004 06:22 PM

Re: try catch(...)
 
Quote:

Originally posted by Sinner6
try {
ReallyUglyFunction(); //throw lots of std::exceptions plus many others including divide by zero or referencing bad memory
}
catch (exception e) {
// catches what I expect
}
catch (...) {
// never catches anything in linux
}
Can you be more specific? Like in actually posting some
code, including the output you get on screen?


Cheers,
Tink

Sinner6 06-25-2004 09:22 AM

I think I have things back under control.
Thanks for all the help.


All times are GMT -5. The time now is 12:14 AM.