Information Technology Reference
In-Depth Information
Therefore, you should be able to write these methods so that they satisfy
the no-throw guarantee by writing defensive code.
In the case of a Dispose method throwing an exception, the system might
now have two exceptions running through the system. The .NET envi-
ronment loses the first exception and throws the new exception. You can't
catch the initial exception anywhere in your program; it was eaten by the
system. This greatly complicates your error handling. How can you recover
from an error you don't see?
The last location for the no-throw guarantee is in delegate targets. When
a delegate target throws an exception, none of the other delegate targets
gets called from the same multicast delegate. The only way around this is
to ensure that you do not throw any exceptions from a delegate target. Let's
state that again: Delegate targets (including event handlers) should not
throw exceptions. Doing so means that the code raising the event cannot
participate in the strong exception guarantee. But here, I'm going to mod-
ify that advice. Item 24 showed how you can invoke delegates so that you
can recover from exceptions. Not everyone does, though, so you should
avoid throwing exceptions in delegate handlers. Just because you don't
throw exceptions in delegates does not mean that others follow that advice;
do not rely on the no-throw guarantee for your own delegate invocations.
It's that defensive programming: You should do the best you can because
other programmers might do the worst they can.
Exceptions introduce serious changes to the control flow of an applica-
tion. In the worst case, anything could have happened—or not happened.
The only way to know what has and hasn't changed when an exception is
thrown is to enforce the strong exception guarantee. Then an operation
either completes or does not make any changes. Finalizers, Dispose(), and
delegate targets are special cases and should complete without allowing
exceptions to escape under any circumstances. As a last word, watch carefully
when swapping reference types; it can introduce numerous subtle bugs.
Item 48: Prefer Safe Code
The .NET runtime has been designed so that malicious code cannot infil-
trate and execute on a remote machine. Yet some distributed systems rely
on downloading and executing code from remote machines. If you might
be delivering your software via the Internet or an intranet, or running it
directly from the Web, you need to understand the restrictions that the
 
 
Search WWH ::




Custom Search