Obtain error message?

W

William Payne

Hello. Consider the following code snippet (pseudo-code).

void foo()
{
/* do stuff */

if fatal error occurs
{
throw "error message";
}
}


try
{
foo();
}
catch(/* what should go here if I want to display the error message from the
throw statement above? */)
{
/* display error message */
}

What do I need to do to if I want to obtain the error message from the
throw-statement? I tried catching std::exception but it didn't catch the
exception. Do I need to derive a new class from std::exception if I want to
display the error messages to the user of the program? That's really all I
need exceptions for right now. If a fatal error occur, throw exception to
break call chain and display error message to the user then exit program
(while logging some debugging information). So do I derive my own exception
type (which would be very simple indeed) or do I use some built-in type or
do I do something completely different?

Thanks

/ William Payne
 
R

Ron Natalie

William Payne said:
throw "error message";
You are throwing type const char*.
catch(/* what should go here if I want to display the error message from the
throw statement above? */)
{
/* display error message */
}

catch(const char* message) { cerr << message << endl; }
I tried catching std::exception but it didn't catch the
exception.

Because you didn't throw a std::exception (or something derived from it).
Do I need to derive a new class from std::exception if I want to
display the error messages to the user of the program?

No, but it might not be a bad idea.
 
W

William Payne

Ron Natalie said:
You are throwing type const char*.


catch(const char* message) { cerr << message << endl; }


Because you didn't throw a std::exception (or something derived from it).


No, but it might not be a bad idea.

Thanks for the swift reply, Ron. I didn't realise that I was throwing a
const char* object, but now I know. The reason for using exceptions in my
program (I am trying to write a small text editor) is to break call chains
in a nice way and display information about the error. The errors are of the
unrecoverable sort and I am using it mainly for debugging purposes. I will
throw const char* objects for now and maybe derive my own exception class
later and incorporate logging of debug information so it's easier for me to
track down causes of exceptions. Again, thanks for the swift and very useful
reply.

/ William Payne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,408
Latest member
AlenaRay88

Latest Threads

Top