Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I get message using exceptions?

Status
Not open for further replies.

sean34

Programmer
Jan 17, 2004
2
0
0
SE
Hello

Im using BB6 and I cant get message from exceptions.

My exception class looks like this:

#include <stdexcept>
#include <string>
using std::string;
using std::eek:ut_of_range;

class ListError : public out_of_range
{
public:
ListError(const string& str = "") : out_of_range(str){}

private:
string str;
};
#endif


*************************************************
In main I have a menu where u can do a lot of operations on the list.
One of them is called first(), which sets the current pointer to point at
the first element. If no element has been inserted an exception must be thrown.

void List::first() throw (ListError)
{
if (!isEmpty())
current = firstNode;
else
throw ListError("Error");
}

So, I call first() without having inserted any elements before.
The message I get from Borland Builder is not "Error" as in "throw ("Error");"
Instead I get "..... raised exception class char* with message 'Exception Object Adress:
0x955C6A'. Process stopped. Use step or run to continue."


So, where is my "Error"?
What am I doing wrong?
 
I think you don't catch raised exceptions at the caller scope, i.e. the code that calls List::first ().

Here's a little example to show what you should do :
Code:
#include <string>
#include <iostream>
using namespace std;

// Dummy class
class A
{
public:
  // Dummy procedure throwing a dummy exception
  void set_something (int a) throw (string)
  {
    throw string ("Crash");
  }
};

// test the catching of the exception
int main ()
{
  A a;

  try
    {
      a.set_something (5);
    }
  catch (string s)
    {
      cout << s << endl;
    }

  return 0;
}

You must code exception handling in try-catch blocks.
Maybe a better solution than raising exceptions in your case is to use assertions, a pre-condition here :
Code:
void List::first() throw (ListError)
{
  assert (!isEmpty());//not_empty

  current = firstNode;
}

The code is clearer, and clients of List::first must check that the List object they are using is not empty. Client's code is clearer too : just a if to test vacuity of the list :
Code:
  List alist;
  // Fill it ...
  if (!alist.isEmpty())
     //ok
  else
     //do something here : error report, etc.

--
Globos
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top