A: With checked exceptions, you have to either catch exceptions
thrown by the methods you call, or mention the exception in the throws
clause of your method.
Because of the tedium of mentioning each exception in the throws clause,
some programmers may take the shortcut of swallowing exceptions.
A: You should only catch exceptions that you are prepared to handle.
Otherwise, if you catch an exception and ignore it (or log it), you are
"swallowing" the exception. As a result, code higher up the call
chain that may be prepared to handle the exception will never see
the exception.
A: No. In fact, C# requires it! Methods in C# cannot specify
the exceptions it may throw. The documentation of the method you wish
to call may mention the list of exceptions you can expect. But this list
of exceptions is not enforced by the compiler, and is not guaranteed to be
exhaustive. Also, since the list of exceptions is not part of the contract,
the method can be revised at any time and a new exception that you
didn't know about can be thrown.
Since there is no previously agreed upon list of exceptions, you are
left with no option but to catch all exceptions if you want to recover
from an exception (such as by offering to connect to an alternate
database if the primary database is down, etc.)
Obviously, if you catch all exceptions, you will end up swallowing some
of them.
A: Often in C#, if you have multiple implementations of an interface, each
of those implementations may have their own disjoint exception hierarchies.
(i.e., the exception hierarchies have no common classes other than
System.Exception.) Example: ADO.NET. This makes it impossible for
generic code (i.e., code that can use any of those implementations) to
recover from exceptions generically without catching all exceptions
(i.e., System.Exception.)
Again, if you catch all exceptions you will end up swallowing some of them.
A: Unchecked exceptions results in shorter but less robust code.
C# Best Practice
Partial solution:
Use Abstract ADO.NET
or other similar libraries
|
[Back to Index]
|