Skip to content

Error Handling

At the highest level, exceptions in .NET MUST NOT be shown directly to a user. All exceptions that are raised SHOULD either be handled (via a catch statement) or allowed to bubble up to a higher level. All exceptions MUST be logged in production if they make it up to the presentation layer.

Errors SHOULD produce meaningful messages for a user. In the case of a website, a page or dialog box detailing an error has occurred SHOULD be presented. In the case of an API, a message without a stack trace SHOULD be presented; as appropriate the response code SHOULD be adjusted to reflect the error (i.e. null object returns 404).

Baseline Standards

See here the MSDN article on Best Practices: https://msdn.microsoft.com/en-us/library/seyhszts(v=vs.110).aspx

Creating Exceptions

In general, exceptions are reserved for exceptional cases and SHOULD NOT be thrown unless neccesary. Execptions MUST be thrown in cases where continuing execution would corrupt data or introduce security flaws.

Defensive Programming

Code SHOULD be protected against common errors. This would include checking for null and validating input prior to it's use. Keep in mind the protection level of your code when validating input; a private protection level has more control over it's inputs than a public protection level which may be invoked by code that is not self-contained in your library.

It can generally be considered safe to use an IEnumerable without null checking.

Back to top