Reputation: 137
When defining exceptions should you have separate exceptions for every type of error that can occur or a more general exception that can be used for multiple error conditions.
For example lets say that I have a class that processes strings and I want to throw exceptions if a string is not the correct format.
Would I create separate exceptions such as:
StringTooLongException, StringContainsIllegalCharactersException, StringTerminationException
or just create a single exception such as
StringFormatException
and indicate the more specific exception with an error code within the exception?
Upvotes: 3
Views: 130
Reputation: 9639
There are lots of existing "generic" exception types in the .Net framework, e.g., System.IO.IOException covers lots of possible IO errors, and System.Data.SqlClient.SqlException is used for reporting lots of differents types of Sql error, so I would say it is OK to use a more generic exception type, preferably one that already exists (don't reinvent the wheel).
Upvotes: 0
Reputation: 77304
That depends. Can the receiver of the exception take any useful action depending on the type? Then yes, it would be nice to have different types. If all he can do is show the error message to the user, then different .NET types are not useful and if something has no use, it should not be done.
Upvotes: 3