15.01.2013 Views

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8 - Back to Basics: Exceptions<br />

Many <strong>of</strong> the exceptions I create are nothing more than marker exceptions - that is, they extend the base<br />

System.Exception class and don't provide further implementation. I liken this to marker interfaces<br />

(or marker attributes), such as the INamingContainer interface. These are particularly useful in<br />

allowing you to avoid swallowing exceptions. Take the following code as an example. If the Save()<br />

method doesn't throw a custom exception when validation fails, we really have little choice but to<br />

swallow all exceptions:<br />

try<br />

{<br />

user.Save();<br />

}<br />

catch<br />

{<br />

Error.Text = user.GetErrors();<br />

Error.Visible = true;<br />

}<br />

//versus<br />

try<br />

{<br />

user.Save();<br />

}<br />

catch(ValidationException ex)<br />

{<br />

Error.Text = ex.GetValidationMessage();<br />

Error.Visible = true;<br />

}<br />

The above example also shows how we can extend exceptions to provide further custom behavior<br />

specifically related to our exceptions. This can be as simple as an ErrorCode, to more complex<br />

information such as a PermissionException which exposes the user's permission and the missing<br />

required permission.<br />

Of course, not all exceptions are tied to the domain. It's common to see more operational-oriented<br />

exceptions. If you rely on a web service which returns an error code, you may very wrap that into your<br />

own custom exception to halt execution (remember, fail fast) and leverage your logging infrastructure.<br />

Actually creating a custom exception is a two step process. First (and technically this is all you really<br />

need) create a class, with a meaningful name, which inherits from System.Exception.<br />

public class UpgradeException : Exception<br />

{<br />

}<br />

You should go the extra step and mark your class with the SerializeAttribute and always provide<br />

at least 4 constructors:<br />

<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />

70

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!