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 />

Throwing Exceptions<br />

There isn't one magic rule to throwing exceptions like there is for catching them (again, that rule is don't<br />

catch exceptions unless you can actually handle them). Nonetheless throwing exceptions, whether or<br />

not they be your own (which we'll cover next), is still pretty simple. First we'll look at the actual<br />

mechanics <strong>of</strong> throwing exceptions, which relies on the throw statement. Then we'll examine when and<br />

why you actually want to throw exceptions.<br />

Throwing Mechanics<br />

You can either throw a new exception, or rethrow a caught exception. To throw a new exception, simply<br />

create a new exception and throw it.<br />

throw new Exception("something bad happened!");<br />

//or<br />

Exception ex = new Exception("something bad happened");<br />

throw ex;<br />

I added the second example because some developers think exceptions are some special/unique case -<br />

but the truth is that they are just like any other object (except they inherit from System.Exception<br />

which in turn inherits from System.Object). In fact, just because you create a new exception<br />

doesn't mean you have to throw it - although you probably always would.<br />

On occasion you'll need to rethrow an exception because, while you can't handle the exception, you still<br />

need to execute some code when an exception occurs. The most common example is having to rollback<br />

a transaction on failure:<br />

ITransaction transaction = null;<br />

try<br />

{<br />

transaction = session.BeginTransaction();<br />

// do some work<br />

transaction.Commit();<br />

}<br />

catch<br />

{<br />

if (transaction != null) { transaction.Rollback(); }<br />

throw;<br />

}<br />

finally<br />

{<br />

//cleanup<br />

}<br />

In the above example our vanilla throw statement makes our catch transparent. That is, a handler up<br />

the chain <strong>of</strong> execution won't have any indication that we caught the exception. In most cases, this is<br />

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

67

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

Saved successfully!

Ooh no, something went wrong!