#begin

When to Use Exceptions

Next up we get to the section I hinted at before and it’s about exceptions. We discussed the mindset of failing fast and the fact funny statement that dead programs tell no lies. David an Andrew rightfully admit that if you throw exceptions at every possible invalid state or input you will end up with some darn ugly code. Especially when your language doesn’t even support exceptions and you need to return exit codes for example. Things can become pretty hairy quickly.

This is exactly what Prof. Ousterhout yells about as well. Take some suffering upon yourself, pull complexity downwards and define errors our of existence.

But what exactly should we throw exceptions for, and what is deemed “exceptional”. David and Andrew say that exceptions should rarely be used to define a program’s normal flow. This is also specifically mentioned by Prof. Ousterhout.

A way to know if the normal flow of you system depends on the use of exceptions is to ask yourself the question if the software is still able to run normally when you remove the exception handling. If it’s not able to run, then you are probably using exceptions in a non exceptional way. Haha, this seems so much like common sense. But it’s actually pretty difficult I guess. Sometime it’s really difficult to check for faulty conditions with mere if statements. A try-catch is more expressive then, but it will create some performance hit as we talked about earlier.

An exception should represent an immediate, nonlocal transfer of control. So if you can cover things with actual code, do it. If you can write your code to remove the need for exceptions, define the errors out of existence, do it. Programs that use exceptions in the normal flow of the code are hard to understand and maintain and often lead to spaghetti code!

Then they mention something really interesting and I’ll quote: “These programs break encapsulation: routines and their callers are more tightly coupled via exception handling”. And that’s most certainly a true statement. Especially when you use typed exceptions you are adding additional dependencies.

 

#end

01010010 01110101 01100010 01100101 01101110

Hey, sorry to bother you but you can subscribe to my blog here.

Never miss a blog post!

You have Successfully Subscribed!