Russ Kiselev
Russ Kiselev

Reputation: 173

c++ exception are not caught by catch(exception type)

Here is a piece of code that I have my exception in:

try {
        hashTable->lookup(bufDescTable[clockHand].file, bufDescTable[clockHand].pageNo, dummyFrame);
    }
    catch (HashNotFoundException *e) {

    }
    catch (HashNotFoundException &e) {

    }
    catch (HashNotFoundException e) {

    }
    catch (...) {

    }

Exception is generated within hashTable->lookup like that:

throw HashNotFoundException(file->filename(), pageNo);

Here is hashTable-lookup method signature

 void BufHashTbl::lookup(const File* file, const PageId pageNo, FrameId &frameNo)  

Exception escalates to top level like it's nobody's business.

I am using Mac(Lion) and Xcode(g++ for compiler)

Any thoughts would be appreciated.

Thanks!

Upvotes: 0

Views: 381

Answers (1)

Michael Anderson
Michael Anderson

Reputation: 73470

We really need a complete example / further info to diagnose this for you.

For example the following version of the code compiles and works for me, outputing HashNotFoundException &

Note the code has some minor changes from your original, but they should not be material.

However it does generate the following warning:

example.cpp: In function ‘int main()’:
example.cpp:42: warning: exception of type ‘HashNotFoundException’ will be caught
example.cpp:38: warning:    by earlier handler for ‘HashNotFoundException’

I'm compiling using i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00) on OS X 10.8.5

#include <iostream>
#include <sstream>

struct BadgerDbException {};
struct PageId {};
struct FrameId {};

struct HashNotFoundException : public BadgerDbException {
  std::string name;
  PageId pageNo;
  HashNotFoundException(const std::string& nameIn, PageId pageNoIn)
    : BadgerDbException(), name(nameIn), pageNo(pageNoIn) {
    }
};

struct HashTable {
  void lookup(void* file, const PageId pageNo, FrameId &frameNo) {
    throw HashNotFoundException("a file", pageNo);
  }
};    

int main() {
  HashTable * hashTable = new HashTable;
  PageId a_Page_ID;
  FrameId dummyFrame;
  try {
    FrameId dummyFrame;
    hashTable->lookup(NULL, a_Page_ID, dummyFrame);
  }
  catch (HashNotFoundException *e) { std::cout<<"HashNotFoundException *"<<std::endl;}
  catch (HashNotFoundException &e) { std::cout<<"HashNotFoundException &"<<std::endl;}
  catch (HashNotFoundException e)  { std::cout<<"HashNotFoundException"<<std::endl; }
  catch (...)                      { std::cout<<"... exception"<<std::endl; }
}

Upvotes: 1

Related Questions