-
Exception Catching
What is the most correct way to throw and catch an exception?
Code:
class Exception; // Has a getMessage() method and a few constructors.
void doSomething(void)
{
throw new Exception("You're screwed.");
}
#include <iostream>
void main(void)
{
try
{
doSomething();
}
catch (Exception *e)
{
std::cerr << e->getMessage() << std::endl;
}
}
Is that good enough? (I think it is the best method because you can delete your exception after you've gotten what you need. Correct me if I'm wrong.)
Or should I perhaps throw it like this:
Code:
throw Exception("You're screwed.");
And catch it either by reference:
Code:
catch (Exception &e)
Or by value:
Code:
catch (Exception e)
I'd like to hear your opinions.
-
Re: Exception Catching
Hi.
If you throw an exception using new you have to deal with memory management. How can you make sure someone is going to deallocate that memory (even yourself didn't do it ;) )? One good way to go is to throw by value (and make sure you don't have code that might throw another exception in your copy constructor). There 're also possiblities of throwing a smart pointer, but you should think whether or not it's really worth it.
When you catch a reference, you should do it by reference. So, you preserve the polymorphism. Below, it is how I would do (your code with those refactorings).
Code:
void doSomething(void)
{
throw Exception("You're screwed.");
}
void main(void)
{
try
{
doSomething();
}
catch (Exception& e)
{
std::cerr << e.getMessage() << std::endl;
}
}
You can find nice tips about that (and other things) in the book "C++ Coding Standards".
-
Re: Exception Catching
throw and catch by reference. Using the "new" operator is unnecessary and wasteful/dangerous. Also, you should catch specific exception types and not a "catch all." In this case, you are creating a new Exception class so maybe it's ok for you.
-
Re: Exception Catching
C++ Faq Lite on the subject.
- petter
-
Re: Exception Catching
ALWAYS
1) Throw by VALUE
2) Catch by Reference
Anything else is simply asking for problems. [e.g. Memory Leaks, Object Slicing]
-
Re: Exception Catching