Article View: comp.std.c++
Article #3377Re: Exceptions and Destructors
From: Paul D. DeRocco
Date: Tue, 20 Feb 1996 18:36
Date: Tue, 20 Feb 1996 18:36
35 lines
2526 bytes
2526 bytes
Although the language doesn't mandate this, it's a good idea to obey the
rule: never, _never_, NEVER throw an exception from within a destructor.
If there's one operation that should be guaranteed to "work", it's
destroying an object. Remember that destructors are automatically called
during stack unwinding when an exception is thrown. If such a destructor
should throw another exception, what should happen? In fact, the
standard states that in this situation, terminate() will be called, and
terminate() is only one notch less violent than abort().
You can, of course, use exceptions _within_ a destructor, as long as you
handle them all. Just don't let them leak out, or you'll be hosed.
If an error might occur during destruction of an object, try to design
in a separate termination function that can be called first. For
instance, say you've got an object that represents an open file, and
destroying the object is supposed to commit any buffers and close the
file. What happens if a disk write occurs during the buffer writing?
The best approach is to design the destructor so that the error is
swallowed, to avoid violating the above rule. If you need to see the
error, supply a commit() member that can be called before destroying the
object, that will detect any disk errors and leave the file object in a
state that can be destroyed without causing any errors.
--
Ciao,
Paul D. DeRocco
---
[ To submit articles: Try just posting with your newsreader. If that fails,
use mailto:std-c++@ncar.ucar.edu
FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html
Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html
Comments? mailto:std.c++-request@ncar.ucar.edu
]
Technical Details
Message-ID:
<3125B9C0.7241@ix.netcom.com>Path:
arc1-ca.pugleaf.net!chronicle.mti.sgi.com!austernReferences:
<BGLENDEN.96Feb14173755@colobus.aoc.nrao.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!chronicle.mti.sgi.com!austern From: "Paul D. DeRocco" <pderocco@ix.netcom.com> Newsgroups: comp.std.c++ Subject: Re: Exceptions and Destructors Date: 20 Feb 1996 10:36:27 PST Organization: Netcom Approved: austern@isolde.mti.sgi.com Message-ID: <3125B9C0.7241@ix.netcom.com> References: <BGLENDEN.96Feb14173755@colobus.aoc.nrao.edu> NNTP-Posting-Host: isolde.mti.sgi.com X-Original-Date: Sat, 17 Feb 1996 06:19:28 -0500 X-Netcom-Date: Sat Feb 17 3:25:55 AM PST 1996 X-Mailer: Mozilla 2.0b6a (Win95; I) X-Auth: PGPMoose V1.1 PGP comp.std.c++ iQBVAwUBMSoUvEy4NqrwXLNJAQFi/QH5ARVYgQC5UnZzVWcgEjzL2cBJNkgBx4JN WfqSWl82lUx2JuyTgeDUHRGnuAGy95OF1nU7EYIK60ZV1BeK1jGyzA== =5PNg Originator: austern@isolde.mti.sgi.com