Exception Handling
Oliver Kullmann
O.Kullmann@Swansea.ac.uk
Fri Jan 17 17:18:00 GMT 2003
> I think it should be done like this:
> throw MyException("method","class","message");
>
> and then catch it:
> try {
> }
> catch(MyException& e) {
> }
>
> because the new operator can throw as well.. can't it?
> m.
>
In "Gotcha #65: Improper Exception Mechanics" from
@Book{Dew2002,
author = {Stephen C. Dewhurst},
title = {C++ Gotchas: Avoiding Common Problems in Coding and Design},
publisher = {Addison-Wesley},
year = 2002,
series = {Professional Computing Series},
address = {Boston},
note = {ISBN 0-321-12518-5; QA76.73.C153 D488 2002},
annote = {Vorhanden.}
}
you can read more on why *anonymous temporary objects* should be thrown,
and caught by const- or non-const *reference* (in the above example
likely e is not altered, and thus "catch(const MyException& e)"
would be better).
To cite from [Dewhurst 2002]:
"When a throw-expression is executed, the runtime exception-handling mechanism
copies the exception object to a temporary in a "safe" location. ...
This means that the temporary will be usable until the last catch clause that
uses the temporary has completed, ... . This is an important property because,
to put it bluntly, when you throw an exception, all hell breaks loose. That
temporary is the calm in the eye of the exception-handling maelstrom.
This is why it's not a good idea to throw a pointer. ...
The address of the [object created by new] on the heap is copied to a safe
location, but the heap memory to which it refers is unprotected."
And you catch exception by reference (const or non-const) to avoid
slicing (and other problems). See Gotcha #65.
Also relevant here is Gotcha #64. And in the free electronic book
http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html
you find also valuable information on exception and how to handle them (volume 2).
(But w.r.t. exception specification the author (Eckel) recommends its use, while in a
recent CUJ article it was recommended NOT to use exception specification.)
Oliver
> > -----Original Message-----
> > From: gcc-help-owner@gcc.gnu.org [mailto:gcc-help-owner@gcc.gnu.org]On
> > Behalf Of Ryan Cuprak
> > Sent: Thursday, January 16, 2003 6:15 PM
> > To: gcc-help@gcc.gnu.org
> > Subject: Exception Handling
> >
> >
> >
> > Hello,
> > Is it safe to throw an exception as such:
> > throw new MyException ( "method","class","message);
> >
> > and then catch it as:
> > try {
> > }
> > catch ( MyException *e ) {
> > //-- do something
> > delete e;
> > }
> > I am just looking for some guidelines on exceptions. In doing
> > google searches
> > for info, I came across an email stating that the implementation
> > of exceptions
> > varies by compiler in that some runtime systems do a binary copy of the
> > exception and then pass it to the catch etc.
> >
> > Thanks,
> > Ryan
> >
More information about the Gcc-help
mailing list