Using Finally to Write Clean Code

If you have done anything more than a simple “Hello World” program in java, you know that one of the biggest pains in the neck is dealing with exceptions and error handling. This is done through the try – catch structure. When the program is running and an exception pops up, code execution stops and goes directly to Catch, do not pass go, do not close your open streams. You can fix this by closing your stream in your catch block.

try
{
	open stream
	do stuff
	close stream
}
catch
{
	print error
	close stream
}

You can see how code has to be repeated to make this work. It is always a bad idea to repeat code, especially when it is unnecessary. What we need is a way to ensure that the closing code is run regardless of whether an exception is thrown or not. The solution is to write a third block of code, the finally block.

try
{
	open stream
	do stuff
}
catch (Exception e)
{
	oh no!
}
finally
{
	close stream
}

Let’s look at the two possible outcomes of the above code. In a nutshell, we will either have an exception or not. In the first case, once the exception happens we jump directly to the catch block and display our errors or whatnot and go then to the finally block and close our streams to make sure that resources are released back to the system. If we have no exception, the catch block is ignored and the finally block is executed. This prevents us from having to duplicate our cleanup code for both cases. When you are writing code that requires you to release resources back to your system, the finally block is a great way to guard yourself from exceptions.

Bryan Young
About Bryan Young
Bryan Young is a staff writer for WebProNews.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>