Recently I took a test at brainbench and got not a bad result (something like 4.5, master degree). I didn’t know the answer only on 1 question (the rest I was sure about or at least I thought I knew the correct answer 🙂 ). The question is:
Which one of the following is NOT a reason to create custom exceptions?
Choice 1
To insert a strong label for later inspection
Choice 2
To strongly-type the purpose of a particular exception
Choice 3
To allow for remote serialization
Choice 4
To process common steps when an exception is created
Choice 5
To add custom properties for custom data propagation
I answered “4” – To process common steps when an exception is created. Which one you think is correct?
Choice 3. The base exception either already supports remoting, or else you deriving from it won’t add remoting.
The “exception” Marc mentions in a comment is as follows; I think it’s not what the test writers had in mind:
In a WCF service, you can allow an unhandled exception to propagate out of the service. WCF will turn it into a SOAP Fault, which may or may not contain details of the unhandled exception, depending on configuration.
Better, would be to recognize certain sets of exceptions and translate them deliberately into SOAP Faults. For instance, a service that operates on database entities could expect that sometimes an entity would not be found; sometimes an attempt to add a new entity would result in a duplicate; sometimes an update attempt would have resulted in an invalid state. Such a service might decide to expose a
NotFoundFault,DuplicateItemFault, andInvalidStateFault.The service would define the three faults as Data Contracts to define their contents:
You would then indicate that particular operations can return such faults:
Finally, you might wrap an exception from the DAL in such a way that WCF will return the particular fault instead:
I think the test developer was trying to get you to think that something special needs to be done in order for an exception to be serialized for remoting to a different AppDomain. This will not be the case if the custom exception was properly implemented, as the supplied .NET exception classes are all serializable. Thus, the ability to serialize is not an excuse to create a custom exception, as the base class should already be serializable.