What kind of exception should I use for "No Record Found" ? (C#)
I've got the following code which retrieves a records details when I click on a table grid:
public ActionResult City(string rk)
{
try
{
var city = _cityService.Get("0001I", rk);
if (city == null)
{
throw new ServiceException("", "Error when fetching city " + rk);
}
}
}
What kind of exception should I use for this "no record found" problem? I see there are different kinds of exception, but I am not sure which would be appropriate or even if I am coding this correctly.
Solution 1:
KeyNotFoundException would be a reasonable choice, and would conform to the Microsoft guideline to:
Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.
However you could consider creating your own Exception
type if (again from the Microsoft guidelines):
... you have an error condition that can be programmatically handled in a different way than any other existing exceptions.
If you do create your own Exception
, you should follow the guidelines for designing custom exceptions, e.g. you should make your Exception
type Serializable.
Solution 2:
You should create your own exception, and maybe call it RecordNotFoundException
in this case.
Solution 3:
Creating your own exception is quite easy. Just make a class, give it a name, extend Exception
or some other exception type, and provide the constructors that you need (just calling the base Exception
constructors).
If you want to add more, you can, but you often don't need to.
If you find yourself creating a number of exceptions for your project you may want to create a base exception type (that extends Exception) which all of your exceptions extend. This is something you might do when writing a library. It would allow someone to catch either a specific exception, or an exception thrown from your library, or any exception.
public class MySuperAwesomeException : Exception
{
public MySuperAwesomeException() : base() { }
public MySuperAwesomeException(string message) : base(message) { }
public MySuperAwesomeException(string message, Exception innerException)
: base(message, innerException) { }
}