Catching exceptions

support for the ARM toolchain
Post Reply
phileee
Posts: 5
Joined: Mon Sep 22, 2008 4:05 pm

Catching exceptions

Post by phileee » Mon Sep 22, 2008 4:12 pm

Hi All,
I am hoping that someone can point out my mistake... I am trying to catch exceptions in order to debug a problem where my app seems to crash.. I am suspecting that memory is not being released, so I am using:
try
{
something created with "new"
}
catch ()
{
print a debug message.
}

I have #define EXCEPTIONS within my code, so I was thinking that the catch() would get any exception from the new. Instead I see the message "terminate called after throwing an instance of 'std::bad_alloc'"
any clues?
thanks.

baaba
Posts: 1
Joined: Sat Oct 20, 2007 6:20 pm

Re: Catching exceptions

Post by baaba » Tue Sep 23, 2008 1:25 pm

catch() doesn't (and shouldn't) compile so I'll assume you used catch(...). That should catch an std::bad_alloc thrown from operator new, but it's possible that the exception never reached your try-catch block because there was an exception specification somewhere along the way that didn't permit std::bad_alloc to propagate, and the unexpected handler was called instead, which in its default form simply leads to a call to terminate, and long-ass run-on sentences are awesome, and you can see if this is the case as follows:

Code: Select all

#include <exception>
#include <iostream>

void g() {
 new char[size_t(-1)];
}

void h() throw() { // exception-specification that permits no exception at all
 new char[size_t(-1)];
}

void f() {
  try {
    // call something that supposedly is throwing std::bad_alloc
    h();
    // g(); // you can also try this and comment out the h() call to see what happens
  }
  catch(std::bad_alloc&) {
    std::cerr << "bad_alloc caught!";
  }
}

void handler() {
  std::cerr << "in unexpected exception handler";
  // this handler is pretty useless though,
  // since you have to throw an exception but there's
  // no way to find out which exception (if any!) might
  // be permitted in the exception specification

  std::terminate();
}

int main() {
  std::set_unexpected(&handler);
  f();
}

The whole exception specification thing is a humongous mess and you should avoid using them. You can find more info on them here: http://www.gotw.ca/publications/mill22.htm
tl;dr for that page:

Moral #1 Never write an exception specification
Moral #2: Except possibly an empty one, but if I were you I’d avoid even that.

Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests