I have made a component that throws Exception. I'm thinking if I should stick with standard throw new Exception
or if I should create specific exceptions.
I also consider user-defined exception as not appealing when it throws exception from Remoting or WCF. if I use standard exception, the caller can receive the exception, if I made a user-defined exception, the caller won't be able to receive the specific exception unless the component's assembly is also deployed to client; however, the client can receive the exception from user-defined exceptions if one catches the user-defined exception from within Remoting and WCF and rethrows it as standard exception, which in turn defeats the purpose of user-defined exception.
When is adding user-defined exception not so useful?
[EDIT]
Sharing my thoughts, I think user-defined exception is a must(at least one) on a component, so when you unit test your own component, you will not receive false positives.
This produces false positives:
[Test]
public void Tag_is_missing()
{
string message = "";
try
{
// Arrange
// this will fail on *nix systems
MyComponentHelper.ParseXml("C:\A.XML");
}
catch(Exception ex)
{
// Act
message = ex.InnerException.Message;
}
// Assert
// How can we be sure that the word "not found" error is from
// xml parsing or if from file loading? Doing Pokemon exception handling
// will lead to ambiguities
Assert.IsTrue(message.Contains("not found"));
}
If you didn't made your own exception, your unit test might receive false positives, the "not found" string could be from your component or from other subsystems of your component. So there goes my case of when one should create user-defined exception.
This won't produce false positives:
[Test]
public void Tag_is_missing()
{
string message = "";
try
{
// Arrange
// this will fail on *nix systems
MyComponentHelper.ParseXml("C:\A.XML");
}
catch(XmlParsingException ex)
{
// Act
message = ex.InnerException.Message;
// Assert
// And now we are more sure that the error didn't come from
// program subsystem; in particular, file subsystem.
Assert.IsTrue(message.Contains("not found"));
}
}
What's left to ponder is when one should create very specific user-defined exceptions. For now, I'll settle first on having just one user-defined exception for my component, unit testings should not yield false positives.