The recommended approach to the none-of-the-above exception?

A

apa

There are a few well-known (?) guidelines to throwing/creating exceptions
(paraphrasing my understanding of it):
1. Don't throw general types like Exception or ApplicationException.
2. Use existing exception classes where it makes sense (ArgumentException
etc).
3. Don't create custom exception types if they don't add anything of value.
(Value can be just being able to catch that exception and nothing else.)

However, where I get confused is where I don't have any specific information
to add about an exception, and don't expect any special exception handling
to occur. For example, say I do a database query, which very unexpectedly
returns an empty result set. I basically just want to

throw new Exception("no data from db");

FxCop will have issues with that though. Should I create a
"MyApplicationException" for the none-of-the-above stuff? It seems to break
rule #3.

Thanks!
 
J

Jon Skeet [C# MVP]

apa said:
There are a few well-known (?) guidelines to throwing/creating exceptions
(paraphrasing my understanding of it):
1. Don't throw general types like Exception or ApplicationException.
2. Use existing exception classes where it makes sense (ArgumentException
etc).
3. Don't create custom exception types if they don't add anything of value.
(Value can be just being able to catch that exception and nothing else.)

However, where I get confused is where I don't have any specific information
to add about an exception, and don't expect any special exception handling
to occur. For example, say I do a database query, which very unexpectedly
returns an empty result set. I basically just want to

throw new Exception("no data from db");

FxCop will have issues with that though. Should I create a
"MyApplicationException" for the none-of-the-above stuff? It seems to break
rule #3.

No, because of the bit in brackets - the type itself (e.g.
MissingDataException) would be useful information. You don't even need
to explicitly catch it for it to be of use - you might choose to break
into code when debugging as soon as that is thrown.

If it feels a bit specific to you, think about an exception which you
can use whenever the database is in an unexpected state -
"UnexpectedDatabaseStateException" or something similar.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top